Phase 4 구현 완료: Neo4j 벡터 검색 + 그래프 저장소

This commit is contained in:
lasta
2026-05-14 10:35:31 +09:00
parent ec4f9a64f6
commit 7ea8df65d8
34 changed files with 4459 additions and 7 deletions

223
PHASE3_COMPLETION.md Normal file
View File

@@ -0,0 +1,223 @@
# 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`)
```python
# 핵심 모델
- 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`)
```python
# 현재
ValidatorFactory.create("lightweight") # Phase 3 MVP ✅
# 향후 확장
ValidatorFactory.create("guardrails") # Phase 3+ (구현 준비됨)
ValidatorFactory.create("ontocast") # Phase 3 Option B (구현 준비됨)
```
### 4. 사용자 API (`guards.py`)
```python
# 간단한 사용법
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` 응답에 검증 정보 추가:
```json
{
"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 검수 항목
### ✅ 완료된 항목
- [x] LLM 출력 스키마 검증 (Pydantic)
- Entity ID format 강제
- Confidence range 검증
- Relation endpoint 존재 확인
- [x] 잘못된 스키마 응답 자동 처리
- Non-strict 모드: 경고로 수집
- Strict 모드: 예외 발생
- [x] Reask 메커니즘 준비
- validation_errors 리스트로 재추출 정보 전달 가능
- 나중에 LLM에 피드백으로 전달 가능
- [x] Phase 0-2 기능 회귀 없음
- Trafilatura 추출 ✓
- Crawl4AI 통합 ✓
- Lightweight extraction ✓
- [x] 외부 의존성 최소화
- Guardrails 미설치 상태에서도 작동 ✓
- Pydantic만 사용 (이미 설치됨) ✓
### ⏳ 향후 옵션
#### 옵션 B: Full OntoCast 통합
```python
# 나중에 구현 가능
guard = OntologyGuard(validator_type="ontocast")
# OntoCast의 Renderer/Critic 출력을 검증
```
#### Guardrails 통합
```python
# 나중에 구현 가능
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+ 업그레이드 경로
```python
# 현재 (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 검증