CCheckpointW3 · RAG_RETRIEVAL
RAG_RETRIEVAL / BM25 → Embedding → Hybrid RRF제출 준비 중

W3

RAG W3 Hackathon

법령 조문 청킹과 근거 검색

법제처 국가법령정보 API의 XML을 법령·조문 구조로 정규화하고, 조문을 항·호 단위로 어떻게 자를지 직접 설계해 청크 순위를 제출합니다. 관련 질의 25개와 미관련 질의 25개를 구분하며, 점수는 검색 판정 60%(검색 품질·완전 근거·NO_RESULT 판별), 증거 항 회수 25%, 청킹 설계 15%입니다. 전부 NO_RESULT이거나 단어 겹침 기본 순위를 그대로 낸 제출은 점수를 받지 못합니다.

METRIC
Retrieval Score
LEVEL
초중급
EST. TIME
2시간
BASELINE
BM25 → Embedding → Hybrid RRF

Start Here / Step 00

데이터와 제출 규격부터 확인하세요

법제처 국가법령정보 XML · law_code:article_no 조문 ID · 조문 text의 start/end 청크 좌표

Dataset · Step 00

데이터셋 받기

queries · sources · sample_ranking + manifest 템플릿·제출 안내(README)를 한 번에 받습니다.

강사 snapshot preflight 후 배포

Output Contract

출력 함수 (선택)

chunks.jsonl
{ "chunk_id": "LAW_CODE:ARTICLE_NO-0", "source_id": "LAW_CODE:ARTICLE_NO", "start": 0, "end": 180, "text_sha256": "..." }

ranking.csv
query_id,rank,chunk_id
M001,1,LAW_CODE:ARTICLE_NO-0

manifest.json
{ "schema_version": 1, ... }
.py 받기

Starter / Step 00b

여기서 출발하세요

기준선 · API collection scaffold + 조문 통째 1청크 예시 (청킹 점수 0, no ranking output)

DATA_GO_KR_LAW_KEY를 설정하고 실행하면 sources.jsonl + manifest.json + chunks.jsonl(조문 통째 1청크 예시)이 만들어집니다. ranking.csv는 만들지 않습니다. 조문을 자르는 방식과 검색기를 직접 구현해 chunk_id 순위를 제출하세요.

From the Lectures · 이 코드가 출발한 강의

1강 · RAG 개요와 검색 파이프라인
API 수집 → 정규화 → chunk → 검색 → 근거 ID 제출의 전체 계약
2강 · 텍스트 전처리와 BM25
질문·문서를 같은 토큰 공간으로 바꾼 뒤 의미 검색과 비교하는 법

rag-w3-law-v2.py · Python standard library · 법령 API 수집·정규화·청크 좌표 scaffold

import hashlib, json, os, re
from datetime import datetime, timezone
from urllib.parse import urlencode, urljoin
from urllib.request import urlopen
from xml.etree import ElementTree as ET

CHALLENGE_SLUG = "rag-w3-law-v2"
SOURCE_URL = "https://apis.data.go.kr/1170000/law/lawSearchList.do"
DETAIL_BASE_URL = "https://www.law.go.kr"
LAWS = [("011357", "개인정보 보호법"), ("001872", "근로기준법"), ("001766", "산업안전보건법"), ("000223", "국민건강증진법"), ("000173", "환경정책기본법"), ("001638", "도로교통법"), ("000187", "장애인복지법")]

def request_xml(url, parameters):
    with urlopen(f"{url}?{urlencode(parameters)}", timeout=30) as response:
        return ET.fromstring(response.read())

def text(node, name):
    child = node.find(f".//{name}")
    return "" if child is None else "".join(child.itertext()).strip()

def plain(node):
    return re.sub(r"\s+", " ", " ".join(node.itertext())).strip()

def collect(service_key):
    sources, requests = [], []
    for law_id, law_name in LAWS:
        parameters = {"serviceKey": service_key, "target": "law", "query": law_name, "numOfRows": 100, "pageNo": 1}
        listing = request_xml(SOURCE_URL, parameters)
        if text(listing, "resultCode") != "00":
            raise RuntimeError(f"{law_name} 목록 API 응답을 확인하세요")
        match = next((row for row in listing.findall(".//law") if text(row, "법령ID") == law_id), None)
        detail_path = "" if match is None else text(match, "법령상세링크")
        if not detail_path:
            raise RuntimeError(f"{law_name} 상세 링크를 찾지 못했습니다")
        detail_url = urljoin(DETAIL_BASE_URL, detail_path.replace("type=HTML", "type=XML"))
        with urlopen(detail_url, timeout=30) as response:
            detail = ET.fromstring(response.read())
        for article in detail.findall(".//조문단위"):
            article_text = plain(article)
            article_no = re.search(r"제\s*(\d+)\s*조(?:의\s*(\d+))?", article_text)
            if not article_no:
                continue
            number = article_no.group(1) + (f"의{article_no.group(2)}" if article_no.group(2) else "")
            sources.append({"source_id": f"{law_id}:{number}", "text": "\n".join([f"법령명: {law_name}", f"법령ID: {law_id}", f"조문: 제{number}조", f"조문제목: {text(article, '조문제목')}", f"시행일자: {text(article, '조문시행일자')}", f"조문내용: {article_text}"])})
        requests.append({"source_url": SOURCE_URL, "parameters": {"target": "law", "query": law_name, "numOfRows": 100, "pageNo": 1}, "result_code": "00"})
    sources = sorted({source["source_id"]: source for source in sources}.values(), key=lambda source: source["source_id"])
    if len(sources) < 300:
        raise RuntimeError(f"수집된 조문이 부족합니다: {len(sources)}개")
    return sources, requests

def make_chunk(chunk_id, source, start, end):
    """조문 하나(sources.jsonl 한 줄)의 text[start:end]를 청크로 정의합니다.
    start, end는 파이썬 문자열 인덱스(글자 수 기준, end는 미포함)이고 text_sha256이 그 구간의 SHA-256입니다.
    청크의 본문은 chunks.jsonl에 넣지 않습니다. 검색기에는 source["text"][start:end]를 쓰세요."""
    piece = source["text"][start:end]
    if not piece:
        raise ValueError(f"{chunk_id}: 빈 청크입니다 (start={start}, end={end})")
    return {"chunk_id": chunk_id, "source_id": source["source_id"], "start": start, "end": end, "text_sha256": hashlib.sha256(piece.encode("utf-8")).hexdigest()}

def write_chunks(chunks):
    """chunks.jsonl을 쓰고 manifest.json의 corpus.chunk_count를 청크 수에 맞춥니다."""
    with open("chunks.jsonl", "w", encoding="utf-8") as output:
        output.write("\n".join(json.dumps(chunk, ensure_ascii=False) for chunk in chunks) + "\n")
    with open("manifest.json", encoding="utf-8") as manifest_file:
        manifest = json.load(manifest_file)
    manifest["corpus"]["chunk_count"] = len(chunks)
    with open("manifest.json", "w", encoding="utf-8") as output:
        json.dump(manifest, output, ensure_ascii=False, indent=2)

def main():
    service_key = os.environ.get("DATA_GO_KR_LAW_KEY", "").strip()
    if not service_key:
        raise RuntimeError("DATA_GO_KR_LAW_KEY 환경변수를 설정한 뒤 다시 실행하세요")
    sources, requests = collect(service_key)
    normalized = "\n".join(f'{source["source_id"]}\t{source["text"]}' for source in sources)
    fingerprint = hashlib.sha256(normalized.encode()).hexdigest()
    with open("sources.jsonl", "w", encoding="utf-8") as output:
        output.write("\n".join(json.dumps(source, ensure_ascii=False) for source in sources) + "\n")
    with open("manifest.json", "w", encoding="utf-8") as output:
        json.dump({"schema_version": 1, "challenge_slug": CHALLENGE_SLUG, "corpus_id": f"sha256:{fingerprint}", "collector": {"collected_at": datetime.now(timezone.utc).isoformat(), "normalizer_version": "1.0.0", "requests": requests}, "corpus": {"source_count": len(sources), "chunk_count": len(sources), "normalized_sha256": fingerprint}, "retriever": {"method": "bm25"}}, output, ensure_ascii=False, indent=2)
    # 기본 chunks.jsonl은 조문 하나를 청크 하나로 둔 형식 예시입니다. 이대로 내면 청킹 점수는 0입니다.
    write_chunks([make_chunk(f'{source["source_id"]}-0', source, 0, len(source["text"])) for source in sources])
    print(f"API로 조문 {len(sources)}개를 수집해 sources.jsonl, manifest.json, chunks.jsonl(조문 통째 1청크 예시)을 만들었습니다.")
    print("이제 조문을 어떻게 자를지 설계해 make_chunk()·write_chunks()로 chunks.jsonl을 다시 만들고,")
    print("그 청크에 BM25·embedding·hybrid 검색기를 적용해 chunk_id 순위의 ranking.csv를 직접 구현하세요.")

if __name__ == "__main__":
    main()

New Here · 강의에서 다루지 않은 부분

조문을 항·호 경계에서 어떻게 자를지 직접 설계하고, 그 청크로 복수 조문 근거의 top 10 순위를 만드는 일

조문 통째 1청크로 만든 BM25 결과를 기준선으로 두고, 항 단위로 자른 청크가 정답 항을 더 정확히 찾는지, 너무 잘게 자르면 어디서 손해인지 비교합니다.

Next Steps

  • 01조문 통째 청크와 항 단위 청크의 증거 항 회수율 비교
  • 02항이 길면 호에서 나누고 짧은 항은 합치는 규칙으로 청크 크기 분포 조정
  • 03embedding 검색과 BM25를 RRF로 결합해 복수 근거의 top 5 회수율 비교
  • 04NO_RESULT 임계값을 한 번만 조정하고 오탐·미탐을 기록

Live Rankings

클래스 리더보드

이해 확인을 통과해 ranked가 된 제출만 표시합니다. 각 수강생의 최고 점수 1개만 순위에 반영됩니다.

순위 기록을 불러오는 중입니다.

Join the Board

제출 → 이해 확인 → 순위 공개

출력값은 서버가 다시 채점합니다. 객관식 3문항 중 2문항 이상과 80자 이상의 실험 회고를 제출하기 전까지 점수는 잠깁니다.

  1. 01랭킹·manifest 검증현재
  2. 02Retrieval 재채점대기
  3. 03이해 확인대기
  4. 04순위 공개대기

Submission Gate

제출 준비 중

미션 브리프는 먼저 확인할 수 있습니다. 강사가 비공개 평가셋과 제출 설정을 공개하면 랭킹·manifest 제출과 이해 확인이 열립니다.

Learning Objectives

이번 미션에서 확인할 것

  1. 01XML의 법령·조문 계층과 시행일을 보존해 source_id를 만든다.
  2. 02조문의 항·호 구조에 맞춰 청크 경계를 설계하고, 조문 통째 청크와 검색 결과를 비교한다.
  3. 03표현이 다른 질문에서 BM25·임베딩·Hybrid RRF의 순위 차이를 비교한다.
  4. 04관련 질의와 corpus 안에 근거가 없는 질의를 구분해 top 10 결과 또는 NO_RESULT를 설명한다.

Output Checklist

제출·학습 산출물

사이트에는 chunks.jsonl, ranking.csv, manifest.json을 업로드합니다. chunks.jsonl에는 조문을 어떻게 잘랐는지(좌표와 해시)만 적고 원문은 넣지 마세요. 수집 API 키·토큰·원문도 넣지 말고, notebook에는 청킹·검색 실험 근거를 남기세요.

  • 사이트 제출chunks.jsonl (chunk_id, source_id, start, end, text_sha256)
  • 실험 기록ranking.csv (query_id, rank, chunk_id)
  • 실험 기록manifest.json (키를 제외한 수집·정규화 기록)
  • 실험 기록재현 가능한 notebook
  • 실험 기록청킹 또는 검색 개선 실험 1건

Original Source

위 ZIP은 학습용 split입니다. 정답이 포함된 원본 전체는 아래 대회에서 확인하세요.

법제처 국가법령정보 Open API 열기 ↗