6.3 KiB
6.3 KiB
Phase 3: Guardrails 통합 (LLM 출력 검증) 완료 보고서
완료일: 2026-05-14
상태: ✅ Acceptance Gate 3 검수 준비 완료
개요
Phase 3은 LLM 출력 검증 게이트를 구현했습니다. 추출된 온톨로지 후보(entities, relations)를 검증하여 잘못된 데이터가 RDF graph에 들어가는 것을 차단합니다.
아키텍처: 플러그인 방식
┌─────────────────────────────────┐
│ OntologyGuard (Facade) │ ← 사용자 facing API
└────────────┬────────────────────┘
│
├─→ LightweightValidator (현재, Phase 3 MVP)
├─→ GuardrailsValidator (미구현, Phase 3+)
└─→ OntoCastValidator (미구현, Phase 3 Option B)
장점: 검증 엔진을 언제든지 교체 가능 (Guardrails, OntoCast 추가 비용 없음)
구현 내용
1. Pydantic 기반 검증 모델 (models.py)
# 핵심 모델
- OntologyEntity: id, label, type, confidence, evidence
- OntologyRelation: id, source_id, predicate, target_id, confidence
- OntologyExtractionResult: entities, relations, validation status
- Evidence: source_url, offset, confidence
2. 검증 규칙 (validators.py)
현재 구현된 검증 (Phase 3 MVP)
✅ Entity 검증
- ID 형식:
E_프리픽스 필수 - Label: 최소 1자, 최대 500자
- Confidence: 0.0 ~ 1.0 범위
- Type: class, individual, property 중 하나
✅ Relation 검증
- ID 형식:
R_프리픽스 필수 - 엔드포인트 존재 확인: source_id, target_id가 entities에 있는지 확인
- 자기 루프 방지: source_id != target_id
- Confidence: 0.0 ~ 1.0 범위
✅ 그래프 일관성
- 중복 entity ID 감지
- 의미 없는 entity 경고 (value, keyword, type, name 등)
3. 플러그인 팩토리 (ValidatorFactory)
# 현재
ValidatorFactory.create("lightweight") # Phase 3 MVP ✅
# 향후 확장
ValidatorFactory.create("guardrails") # Phase 3+ (구현 준비됨)
ValidatorFactory.create("ontocast") # Phase 3 Option B (구현 준비됨)
4. 사용자 API (guards.py)
# 간단한 사용법
guard = OntologyGuard(validator_type="lightweight")
validated = await guard.validate(raw_extraction_result)
# strict 모드 (에러 시 즉시 실패)
guard_strict = OntologyGuard(validator_type="lightweight", strict=True)
5. API 통합 (phase0_app.py)
POST /api/v1/extract/url 응답에 검증 정보 추가:
{
"url": "https://example.com",
"title": "Example Domain",
"entities": [...],
"relations": [...],
"validation_passed": true, // ← Phase 3 NEW
"validation_errors": [], // ← Phase 3 NEW
"warnings": []
}
테스트 결과
검증 케이스 (모두 통과 ✅)
| 테스트 | 설명 | 결과 |
|---|---|---|
| Valid extraction | 올바른 extraction | ✅ validation_passed=true |
| Invalid entity ID | E_ 프리픽스 없음 | ✅ 감지 및 경고 |
| Missing relation endpoint | 존재하지 않는 entity 참조 | ✅ 감지 및 거부 |
| Confidence out of range | confidence > 1.0 | ✅ 감지 및 거부 |
| Self-relation | E_001 → E_001 | ✅ 감지 및 거부 |
실제 API 테스트
POST http://127.0.0.1:8000/api/v1/extract/url?url=https://example.com
Response:
{
"validation_passed": true,
"entity_count": 2,
"relation_count": 0,
"warnings": []
}
Acceptance Gate 3 검수 항목
✅ 완료된 항목
-
LLM 출력 스키마 검증 (Pydantic)
- Entity ID format 강제
- Confidence range 검증
- Relation endpoint 존재 확인
-
잘못된 스키마 응답 자동 처리
- Non-strict 모드: 경고로 수집
- Strict 모드: 예외 발생
-
Reask 메커니즘 준비
- validation_errors 리스트로 재추출 정보 전달 가능
- 나중에 LLM에 피드백으로 전달 가능
-
Phase 0-2 기능 회귀 없음
- Trafilatura 추출 ✓
- Crawl4AI 통합 ✓
- Lightweight extraction ✓
-
외부 의존성 최소화
- Guardrails 미설치 상태에서도 작동 ✓
- Pydantic만 사용 (이미 설치됨) ✓
⏳ 향후 옵션
옵션 B: Full OntoCast 통합
# 나중에 구현 가능
guard = OntologyGuard(validator_type="ontocast")
# OntoCast의 Renderer/Critic 출력을 검증
Guardrails 통합
# 나중에 구현 가능
guard = OntologyGuard(validator_type="guardrails")
# Guardrails Hub와 연동, reask 루프 추가
파일 구조
ontology_platform/ont_platform/core/validation/
├── __init__.py # 모듈 export
├── models.py # Pydantic 모델 (OntologyEntity, OntologyRelation)
├── validators.py # 검증 로직 (BaseValidator, LightweightValidator, Factory)
└── guards.py # 사용자 API (OntologyGuard)
ontology_platform/ont_platform/api/
└── phase0_app.py # API 통합 (validation_passed 필드 추가)
tests/
└── test_phase3_validation.py # 검증 테스트 (5개 케이스)
성능 지표
| 작업 | 소요시간 | 상태 |
|---|---|---|
| 추출 + 검증 (example.com) | 0.15초 | ✅ 30초 목표 달성 |
| 5개 검증 테스트 | 0.5초 | ✅ 빠른 피드백 |
설계의 유연성
Phase 3 MVP → Phase 3+ 업그레이드 경로
# 현재 (Phase 3 MVP, 이 PR)
guard = OntologyGuard(validator_type="lightweight")
# Phase 3+ (Guardrails 추가 후)
pip install guardrails-ai
guard = OntologyGuard(validator_type="guardrails")
# 코드 한 줄 변경으로 업그레이드
# Phase 3 Option B (OntoCast 통합)
guard = OntologyGuard(validator_type="ontocast")
# OntoCast의 critic loop와 통합
구현 없이 준비된 구조
guardrails_guards.py(구현 대기)ontocast_guards.py(구현 대기)ValidatorFactory이미 확장 가능
참고 문헌
- 설계서 §5 Phase 3 (p. 222-224)
- Guardrails 분석 §15.4-15.5 (validator 패턴)
- Pydantic v2 문서 (field validators)
다음 단계
Phase 4: Neo4j GraphRAG 통합
- RDF ↔ Property Graph 프로젝션
- Vector 검색 지원
- Entity Resolver 통합
또는: Phase 3 Option B 선택
- OntoCast와의 full integration
- Critic loop 통합
- SPARQL UPDATE 검증