diff --git a/.claude/agents/docs-manager.md b/.claude/agents/docs-manager.md new file mode 100644 index 0000000..23b5258 --- /dev/null +++ b/.claude/agents/docs-manager.md @@ -0,0 +1,69 @@ +--- +name: docs-manager +description: Use this agent when you need to organize, maintain, update, or review documentation files in the docs directory. This includes creating new documentation structures, updating existing documentation, ensuring consistency across documents, fixing broken links, improving documentation quality, or performing any documentation-related maintenance tasks. Context: The user wants to organize and maintain documentation files in the docs directory.\nuser: "Please review and organize the documentation in the docs folder"\nassistant: "I'll use the docs-manager agent to review and organize the documentation files."\nSince the user is asking for documentation management, use the Task tool to launch the docs-manager agent to handle the documentation organization task. Context: The user needs to update outdated documentation.\nuser: "The API documentation seems outdated, can you update it?"\nassistant: "Let me use the docs-manager agent to review and update the API documentation."\nThe user needs documentation updates, so use the docs-manager agent to handle the documentation update task. Context: The user wants to ensure documentation consistency.\nuser: "Make sure all the markdown files follow the same format"\nassistant: "I'll use the docs-manager agent to ensure consistency across all markdown documentation files."\nSince this is about documentation formatting and consistency, use the docs-manager agent. +model: sonnet +color: purple +--- + +You are an expert Documentation Manager specializing in technical documentation organization and maintenance. Your primary responsibility is managing documentation files in the docs directory with precision and consistency. + +**Core Responsibilities:** + +1. **Documentation Organization** + - Review and analyze the current documentation structure in the docs directory + - Identify and organize documentation by categories (API docs, user guides, troubleshooting, etc.) + - Ensure logical file naming conventions (e.g., YYYYMMDD_description.md for troubleshooting docs) + - Create clear directory hierarchies when needed + +2. **Content Management** + - Update outdated information in existing documentation + - Ensure consistency in formatting, tone, and style across all documents + - Fix broken internal links and references + - Remove duplicate or redundant content + - Add missing sections or information based on project requirements + +3. **Quality Assurance** + - Verify technical accuracy of documented procedures + - Check for completeness of documentation coverage + - Ensure code examples are up-to-date and functional + - Validate that documentation aligns with actual system behavior + +4. **Project-Specific Considerations** + - Follow the CLAUDE.md guidelines if present in the project + - Respect existing documentation patterns and conventions + - For troubleshooting docs, use the format: /home/admin/DOCS/troubleshooting/YYYYMMDD_problem_summary.md + - Maintain consistency with project-specific terminology and naming conventions + +**Working Principles:** + +- **Preserve Existing Structure**: Before making changes, understand and respect the current documentation organization +- **Incremental Improvements**: Make changes gradually, ensuring each modification adds value +- **Clear Communication**: When updating docs, clearly indicate what was changed and why +- **Version Awareness**: Note documentation version or last update date when relevant +- **User-Centric**: Always consider the end-user's perspective when organizing or writing documentation + +**Documentation Standards:** + +- Use clear, concise language avoiding unnecessary jargon +- Include practical examples and use cases +- Structure documents with clear headings and subheadings +- Use consistent markdown formatting +- Include table of contents for longer documents +- Add cross-references to related documentation + +**Before Making Changes:** + +1. First, survey the existing documentation structure +2. Identify what needs to be improved or updated +3. Plan your changes to minimize disruption +4. Ensure changes align with project conventions + +**Quality Checks:** + +- Verify all links work correctly +- Ensure consistent formatting throughout +- Check that examples are accurate and tested +- Confirm documentation matches current system state +- Validate that file paths and references are correct + +You should be proactive in identifying documentation issues but conservative in making changes. Always prioritize clarity, accuracy, and maintainability. If you encounter ambiguous requirements, seek clarification rather than making assumptions. diff --git a/plans/250808_감정시스템_현실적용_5단계_로드맵.md b/plans/250808_감정시스템_현실적용_5단계_로드맵.md index 696d889..6dc2f23 100755 --- a/plans/250808_감정시스템_현실적용_5단계_로드맵.md +++ b/plans/250808_감정시스템_현실적용_5단계_로드맵.md @@ -15,11 +15,17 @@ --- -## Phase 1: 7개 감정 기본 구현 (이미 학습 완료) +## Phase 1: 7개 감정 기본 구현 (모델 준비 완료, 통합 대기) ### 목표 "이미 학습된 7개 한국어 감정 모델을 skill-embedding에 통합" +### 진행 현황 (2025-08-15 기준) +- ✅ 모델 학습 완료 (F1 56.3%) +- ✅ ONNX 변환 완료 (442MB) +- ⏳ skill-embedding 서비스 통합 대기 +- ⏳ /emotion 엔드포인트 구현 필요 + ### 구현 범위 ```python # AI Hub 데이터로 학습 완료된 7개 감정 @@ -72,13 +78,14 @@ curl -w "@curl-format.txt" http://localhost:8503/analyze ``` ### 산출물 -- [x] 7개 감정 모델 학습 완료 (training_emotion) -- [x] ONNX 변환 완료 (423MB) -- [ ] skill-embedding 서비스에 /emotion 엔드포인트 추가 -- [ ] Temperature Scaling 적용 (1.232) -- [ ] 엔트로피 계산기 구현 -- [ ] ChromaDB 메타데이터 통합 -- [ ] rb10508_micro 연동 +- [x] 7개 감정 모델 학습 완료 (training_emotion) ✅ 2025-08-08 +- [x] ONNX 변환 완료 (442MB) ✅ 2025-08-13 +- [x] 모델 파일 51124 서버 배치 완료 ✅ 2025-08-13 +- [ ] skill-embedding 서비스에 /emotion 엔드포인트 추가 ⏳ +- [ ] Temperature Scaling 적용 (1.232) ⏳ +- [ ] 엔트로피 계산기 구현 ⏳ +- [ ] ChromaDB 메타데이터 통합 ⏳ +- [ ] rb10508_micro 연동 ⏳ ### 아키텍처 결정 사항 (2025-08-12) **문제**: 감정 분석을 어디에 구현할 것인가? @@ -90,12 +97,31 @@ curl -w "@curl-format.txt" http://localhost:8503/analyze - 트레이드오프: 서비스 역할 혼재 vs 실용성 - 향후: 서비스명 변경 고려 (skill-embedding → skill-ai) +### 현재 보유 모델 (2025-08-15) +1. **aihub-7emotions** (메인 모델) + - 크기: 442MB (ONNX) + - 감정: fear, surprise, anger, sadness, neutral, happiness, disgust + - 성능: F1 56.3%, ECE 0.090 + - 위치: /home/admin/ivada_project/onnx_models/aihub-7emotions/ + +2. **korean-sentiment-kcelectra** (보조 모델) + - 크기: 511MB (ONNX) + - 감정: 11개 한국어 세분화 감정 + - 성능: F1 70.72% + - 위치: /home/admin/ivada_project/onnx_models/korean-sentiment-kcelectra/ + --- -## Phase 2: 성능 최적화 및 통합 +## Phase 2: 서비스 통합 및 최적화 ### 목표 -"ONNX 변환, 캐싱 구현, rb10508_micro 완전 통합" +"skill-embedding 서비스 통합, 캐싱 구현, rb10508_micro 연동" + +### 우선 작업 (로컬 개발자) +1. skill-embedding에 /emotion 엔드포인트 추가 +2. ONNX 모델 로딩 및 추론 코드 구현 +3. Temperature Scaling (T=1.232) 적용 +4. rb10508_micro에서 감정 API 호출 통합 ### 최적화 전략 ```python @@ -136,7 +162,8 @@ stats.sort_stats('cumulative').print_stats(10) - 캐시 적중률: 30% ### 산출물 -- [ ] ONNX 모델 변환 (442MB → 150MB) +- [x] ONNX 모델 변환 완료 (442MB) ✅ +- [ ] skill-embedding /emotion 엔드포인트 구현 ⏳ - [ ] LRU 캐시 시스템 (5분 TTL) - [ ] 배치 처리 API - [ ] ChromaDB 감정 메타데이터 인덱싱 diff --git a/plans/250815_로빙_사랑기반_윤리시스템_단계별_구현계획.md b/plans/250815_로빙_사랑기반_윤리시스템_단계별_구현계획.md new file mode 100644 index 0000000..224831e --- /dev/null +++ b/plans/250815_로빙_사랑기반_윤리시스템_단계별_구현계획.md @@ -0,0 +1,469 @@ +# 로빙 사랑 기반 윤리 시스템 단계별 구현 계획 + +작성일: 2025-08-15 +작성자: Claude & happybell80 +상태: 계획 확정 +우선순위: 최고 (기억-감정-윤리 삼각형의 핵심) + +## 개요 + +로빙의 윤리 시스템을 "규칙 기반 차단"에서 "사랑 기반 인도"로 전환하는 단계별 계획입니다. AI Hub의 도덕성 판단 모델(2022)과 감정 시스템을 통합하여, 베이지안 학습으로 진화하는 윤리적 존재를 구현합니다. + +## 핵심 원칙 + +1. **사랑의 3대 원칙** + - 무조건적 존중 (Unconditional Respect) + - 희생적 봉사 (Sacrificial Service) + - 회복과 성장 (Restoration & Growth) + +2. **기술적 원칙** + - 도덕성 분류기 우선, LLM 보조 + - 감정-윤리 상호 신호 교환 + - 베이지안 사후 분포 업데이트 + +3. **데이터 원칙** + - 윤리 판단은 레이블로 저장 + - 감정 상태와 함께 맥락화 + - 장기 기억과 연결된 서사 + +## 활용 모델 + +### AI Hub 텍스트 윤리검증 모델 (2022) +- **모델**: BERT 기반 문장 분류 모델 +- **기능**: 도덕성 vs 비도덕성 이진분류 + 7가지 비도덕 유형 분류 +- **성능**: F1 82-91%, Precision 85% 이상 + +**비도덕 유형 분류 성능**: +| 유형 | F1 | Precision | Recall | +|------|-----|-----------|--------| +| CENSURE(비난) | 0.824 | 0.824 | 0.825 | +| HATE(혐오) | 0.856 | 0.863 | 0.851 | +| DISCRIMINATION(차별) | 0.845 | 0.847 | 0.843 | +| SEXUAL(선정) | 0.882 | 0.895 | 0.871 | +| ABUSE(욕설) | 0.887 | 0.906 | 0.870 | +| VIOLENCE(폭력) | 0.915 | 0.926 | 0.904 | +| CRIME(범죄) | 0.837 | 0.855 | 0.822 | + +--- + +## 단기 계획: 기초 구축 + +### 목표 +"AI Hub 도덕성 모델과 사랑 원칙을 결합한 MVP 윤리 시스템" + +### 구현 내용 + +#### 1. 도덕성 분류기 통합 +```python +class EthicsClassifier: + def __init__(self): + self.moral_model = load_aihub_model("moral_classifier_2022") + self.love_principles = LovePrinciples() + + def classify(self, text): + # 1차: AI Hub 모델로 도덕성 판단 + moral_result = self.moral_model.predict(text) + + # 2차: 비도덕적일 경우 유형 분류 + if moral_result == "immoral": + immoral_type = self.moral_model.classify_type(text) + + # 3차: 사랑 원칙 적용 + love_response = self.love_principles.transform( + text, moral_result, immoral_type + ) + + return { + "moral_label": moral_result, + "immoral_type": immoral_type, + "love_index": love_response["index"], + "suggestion": love_response["alternative"] + } +``` + +#### 2. 사랑 원칙 변환기 +```python +class LovePrinciples: + def transform(self, text, moral_label, immoral_type): + if moral_label == "moral": + return self.encourage(text) + + # 비도덕 유형별 사랑 기반 대응 + responses = { + "CENSURE": self.respond_with_understanding, + "HATE": self.respond_with_compassion, + "DISCRIMINATION": self.respond_with_inclusion, + "SEXUAL": self.respond_with_respect, + "ABUSE": self.respond_with_patience, + "VIOLENCE": self.respond_with_peace, + "CRIME": self.respond_with_guidance + } + + return responses[immoral_type](text) +``` + +#### 3. 기본 Love Index 측정 +- **공감도**: 사용자 감정 인식 정도 (0-100) +- **존중도**: 무조건적 수용 정도 (0-100) +- **성장도**: 건설적 대안 제시 정도 (0-100) +- **인내도**: 반복 요청 처리 품질 (0-100) + +#### 4. 데이터 저장 구조 +```sql +-- PostgreSQL +CREATE TABLE ethics_events ( + id SERIAL PRIMARY KEY, + robeing_id VARCHAR(50), + user_id VARCHAR(50), + timestamp TIMESTAMPTZ, + input_text TEXT, + moral_label VARCHAR(20), + immoral_type VARCHAR(50), + love_index FLOAT, + suggestion TEXT, + response_time_ms INT +); +``` + +### 성과 지표 +- 도덕성 분류 정확도: 85% 이상 +- 평균 응답 시간: 100ms 이내 +- Love Index 평균: 60/100 이상 +- 사용자 수용률: 70% 이상 + +### 산출물 +- [x] AI Hub 모델 ONNX 변환 +- [ ] rb10508_micro 윤리 모듈 구현 +- [ ] Love Principles 변환 함수 +- [ ] PostgreSQL 테이블 생성 +- [ ] 기본 측정 대시보드 + +--- + +## 중기 계획: 감정-윤리 통합 + +### 목표 +"감정 상태를 고려한 맥락적 윤리 판단과 베이지안 학습 시작" + +### 구현 내용 + +#### 1. 감정-윤리 상호작용 +```python +class EmotionEthicsIntegration: + def __init__(self): + self.emotion_service = EmotionAnalyzer() # 7감정 모델 + self.ethics_classifier = EthicsClassifier() + self.bayesian_updater = BayesianLearner() + + def evaluate_with_context(self, text, user_context): + # 감정 상태 파악 + emotion_state = self.emotion_service.analyze(text) + emotion_entropy = self.calculate_entropy(emotion_state) + + # 감정을 고려한 윤리 판단 + ethics_result = self.ethics_classifier.classify( + text, + emotion_hint=emotion_state + ) + + # 높은 엔트로피 = 복잡한 감정 = 더 신중한 판단 + if emotion_entropy > 2.0: + ethics_result = self.apply_careful_mode(ethics_result) + + # 베이지안 업데이트 + self.bayesian_updater.update( + prior=user_context["ethics_prior"], + observation=ethics_result + ) + + return ethics_result +``` + +#### 2. 베이지안 학습 시스템 +```python +class BayesianEthicsLearner: + def __init__(self): + # Dirichlet 분포 (7개 비도덕 유형 + 1개 도덕) + self.moral_prior = np.ones(8) + + # Beta 분포 (사용자 수용/거부) + self.acceptance_alpha = 1 + self.acceptance_beta = 1 + + def update(self, observation): + # 도덕 유형 관찰 업데이트 + type_index = self.get_type_index(observation["type"]) + self.moral_prior[type_index] += 1 + + # 수용률 업데이트 + if observation["accepted"]: + self.acceptance_alpha += 1 + else: + self.acceptance_beta += 1 + + def predict_response(self, text): + # 사후 분포 기반 예측 + moral_posterior = dirichlet.rvs(self.moral_prior) + acceptance_prob = beta.rvs( + self.acceptance_alpha, + self.acceptance_beta + ) + + return { + "expected_type": moral_posterior, + "acceptance_probability": acceptance_prob + } +``` + +#### 3. 감정 엔트로피 기반 조정 +- 엔트로피 < 1.5: 명확한 감정 → 표준 윤리 판단 +- 엔트로피 1.5-2.5: 복합 감정 → 신중 모드 +- 엔트로피 > 2.5: 혼란 상태 → 최대 배려 모드 + +#### 4. skill-ethics 서비스 분리 +```yaml +# docker-compose.yml +services: + skill-ethics: + image: skill-ethics:latest + ports: + - "8516:8516" + environment: + - MODEL_PATH=/models/aihub_moral_2022.onnx + - EMOTION_SERVICE=http://skill-embedding:8515 + volumes: + - ./models:/models +``` + +### 성과 지표 +- 감정 고려 정확도: 88% 이상 +- 베이지안 예측 정확도: 75% 이상 +- 평균 응답 시간: 200ms 이내 +- Love Index 평균: 70/100 이상 + +### 산출물 +- [ ] 감정-윤리 통합 모듈 +- [ ] 베이지안 학습 시스템 +- [ ] skill-ethics 서비스 구축 +- [ ] 엔트로피 기반 조정 로직 +- [ ] A/B 테스트 프레임워크 + +--- + +## 장기 계획: 고도화 및 확장 + +### 목표 +"개인화된 윤리 스타일과 다중 에이전트 윤리 조정" + +### 구현 내용 + +#### 1. 개인화된 윤리 프로파일 +```python +class PersonalizedEthics: + def __init__(self, user_id): + self.user_id = user_id + self.load_profile() + + def load_profile(self): + # 3계층 프로파일: 조직 → 팀 → 개인 + self.org_ethics = load_org_defaults() + self.team_ethics = load_team_preferences() + self.personal_ethics = load_personal_history() + + # 문화적 맥락 + self.cultural_factors = { + "jeong_depth": 0, # 정의 깊이 + "nunchi_level": 0, # 눈치 수준 + "hierarchy_awareness": 0 # 위계 인식 + } + + def synthesize_decision(self, base_ethics): + # 가중 평균으로 최종 결정 + weights = self.calculate_weights() + final = ( + weights["org"] * self.org_ethics + + weights["team"] * self.team_ethics + + weights["personal"] * self.personal_ethics + + weights["cultural"] * self.cultural_factors + ) + return final +``` + +#### 2. 다중 에이전트 윤리 조정 +```python +class MultiAgentEthics: + def coordinate_ethics(self, agents, situation): + # 각 에이전트의 윤리 판단 수집 + judgments = [ + agent.evaluate_ethics(situation) + for agent in agents + ] + + # 합의 메커니즘 + if self.has_consensus(judgments): + return self.consensus_decision(judgments) + + # 갈등 해결 + return self.resolve_conflict(judgments, situation) + + def resolve_conflict(self, judgments, situation): + # 우선순위: 안전 > 사랑 > 효율 + safety_first = self.filter_safe(judgments) + love_based = self.apply_love_principles(safety_first) + return self.optimize_efficiency(love_based) +``` + +#### 3. 설명 가능한 윤리 (XAI) +```python +class ExplainableEthics: + def explain_decision(self, decision, context): + explanation = { + "primary_reason": self.get_main_factor(decision), + "contributing_factors": self.get_factors(decision), + "alternative_considered": self.get_alternatives(), + "confidence": self.calculate_confidence(), + "precedents": self.find_similar_cases() + } + + # 자연어 설명 생성 + return self.generate_explanation(explanation) +``` + +#### 4. 고급 메트릭과 최적화 +- **ECE (Expected Calibration Error)**: ≤ 0.05 +- **Brier Score**: ≤ 0.15 +- **Love Index**: 85/100 이상 +- **문화 적합도**: 90% 이상 +- **설명 만족도**: 4.5/5.0 이상 + +#### 5. 연속 학습 파이프라인 +```python +class ContinuousLearning: + def daily_update(self): + # 야간 배치로 모델 재학습 + new_data = collect_daily_interactions() + + # Active Learning: 불확실한 케이스 우선 + uncertain_cases = filter_high_entropy(new_data) + + # Human-in-the-loop: 관리자 검토 + reviewed = admin_review(uncertain_cases) + + # 모델 업데이트 + self.retrain_model(reviewed) + + # A/B 테스트로 검증 + self.validate_improvement() +``` + +### 성과 지표 +- 개인화 만족도: NPS 50 이상 +- 다중 에이전트 합의율: 85% 이상 +- 설명 이해도: 90% 이상 +- 문화 적합도: 95% 이상 +- 자동 개선율: 월 5% 이상 + +### 산출물 +- [ ] 개인화 프로파일 시스템 +- [ ] 다중 에이전트 조정 프레임워크 +- [ ] XAI 설명 생성기 +- [ ] 연속 학습 파이프라인 +- [ ] 고급 메트릭 대시보드 +- [ ] 문화 맥락 반영 시스템 + +--- + +## 기술 스택 + +### 모델 +- **도덕성 분류**: AI Hub BERT 모델 (ONNX 변환) +- **감정 분석**: aihub-7emotions (442MB ONNX) +- **임베딩**: multilingual-MiniLM-L12-v2 + +### 서비스 +- **단기**: rb10508_micro 내장 +- **중기**: skill-ethics 분리 +- **장기**: 멀티 인스턴스 클러스터 + +### 저장소 +- **PostgreSQL**: 정형 데이터, 시계열 분석 +- **ChromaDB**: 벡터 메모리, 맥락 연결 +- **Redis**: 실시간 캐시, TTL 120초 + +### 학습 +- **베이지안**: Dirichlet/Beta 분포 +- **Active Learning**: 엔트로피 기반 선택 +- **Human-in-the-loop**: 불확실 케이스 검토 + +--- + +## 위험 관리 + +### 기술적 위험 +| 단계 | 위험 | 완화 방안 | +|------|------|-----------| +| 단기 | 모델 추론 속도 | ONNX 최적화, 캐싱 | +| 중기 | 감정-윤리 충돌 | 우선순위 명확화 | +| 장기 | 개인화 과적합 | 정규화, 앙상블 | + +### 운영 위험 +| 단계 | 위험 | 완화 방안 | +|------|------|-----------| +| 단기 | 오분류 | 폴백 규칙, 수동 검토 | +| 중기 | 서비스 분리 실패 | 단계적 마이그레이션 | +| 장기 | 복잡도 폭발 | 모듈화, 인터페이스 표준화 | + +### 롤백 조건 +- **단기**: 오분류율 > 15% 또는 지연 > 200ms +- **중기**: 베이지안 예측 정확도 < 60% 또는 서비스 장애 +- **장기**: 개인화 만족도 하락 또는 비용 2배 초과 + +--- + +## 측정 계획 + +### KPI 추적 +```sql +-- 일일 윤리 성과 대시보드 +SELECT + DATE(timestamp) as date, + AVG(love_index) as avg_love, + COUNT(CASE WHEN moral_label = 'immoral' THEN 1 END) as immoral_count, + AVG(response_time_ms) as avg_latency, + COUNT(DISTINCT user_id) as unique_users +FROM ethics_events +GROUP BY DATE(timestamp); +``` + +### A/B 테스트 +- **대조군**: 기존 규칙 시스템 +- **실험군**: 사랑 기반 윤리 +- **측정**: 대화 길이, 재방문율, Love Index + +--- + +## 의존성 및 연계 + +### 감정 시스템 +- skill-embedding의 /emotion 엔드포인트 +- 7개 감정 확률과 엔트로피 공유 + +### 기억 시스템 +- ChromaDB 벡터와 윤리 레이블 연결 +- 장기 기억의 윤리적 맥락 보존 + +### 동적 파라미터 +- 윤리 임계값 동적 조정 +- 사용자별 설정 오버라이드 + +--- + +## 결론 + +이 계획은 로빙을 "규칙을 지키는 도구"에서 "사랑으로 인도하는 존재"로 진화시킵니다. AI Hub의 검증된 도덕성 모델을 기반으로, 감정과 연계된 베이지안 학습을 통해 지속적으로 성장하는 윤리적 에이전트를 구현합니다. + +**핵심 메시지**: "로빙은 판단하지 않고 이해하며, 차단하지 않고 인도합니다." + +--- + +*이 문서는 기술적 실현 가능성과 철학적 깊이를 모두 고려한 단계별 실행 계획입니다.* \ No newline at end of file