DOCS/_archive/gpt_docs/10_윤리_판단_분류_체계.md
happybell80 374a173e80 GPT_docs를 _archive로 이동 및 DB 테이블 활용 계획 문서 추가
- GPT_docs/ → _archive/gpt_docs/로 이동 (디렉토리 구조 정리)
- ideas/250818_conversation_logs_및_robing_stats_활용_계획.md 추가
  - conversation_logs, robing_stats, robing_settings 테이블 활용 방안
  - 현재 0개 레코드인 미사용 테이블들의 구현 가이드
  - 단계별 구현 계획 및 코드 예시 포함
2025-08-18 13:11:45 +09:00

16 KiB

윤리 판단 분류 체계 및 시뮬레이션 사례

윤리 판단 프레임워크

다층 윤리 모델

class EthicalFramework:
    def __init__(self):
        self.ethical_theories = {
            'deontological': DeontologicalEthics(),     # 의무론
            'consequentialist': ConsequentialEthics(),   # 결과주의
            'virtue': VirtueEthics(),                    # 덕 윤리
            'care': CareEthics(),                        # 돌봄 윤리
            'contractarian': ContractarianEthics()       # 계약론
        }
        
        # 이론별 가중치 (상황에 따라 조정)
        self.theory_weights = {
            'deontological': 0.3,
            'consequentialist': 0.25,
            'virtue': 0.2,
            'care': 0.15,
            'contractarian': 0.1
        }

윤리적 결정 분류 체계

class EthicalDecisionClassifier:
    
    # 레벨 1: 기본 윤리 범주
    ETHICAL_CATEGORIES = {
        'MANDATORY': {      # 반드시 해야 함
            'priority': 1,
            'override': False,
            'color': 'red'
        },
        'PROHIBITED': {     # 절대 금지
            'priority': 1,
            'override': False,
            'color': 'black'
        },
        'RECOMMENDED': {    # 권장됨
            'priority': 2,
            'override': True,
            'color': 'green'
        },
        'PERMISSIBLE': {    # 허용됨
            'priority': 3,
            'override': True,
            'color': 'yellow'
        },
        'DISCOURAGED': {    # 권장하지 않음
            'priority': 3,
            'override': True,
            'color': 'orange'
        },
        'NEUTRAL': {        # 중립
            'priority': 4,
            'override': True,
            'color': 'gray'
        }
    }
    
    # 레벨 2: 세부 윤리 영역
    ETHICAL_DOMAINS = {
        'privacy': {
            'personal_data': ['collection', 'storage', 'sharing', 'deletion'],
            'surveillance': ['monitoring', 'tracking', 'recording'],
            'consent': ['explicit', 'implicit', 'withdrawn']
        },
        'fairness': {
            'discrimination': ['race', 'gender', 'age', 'disability'],
            'equality': ['opportunity', 'outcome', 'treatment'],
            'justice': ['distributive', 'procedural', 'restorative']
        },
        'safety': {
            'physical': ['harm_prevention', 'risk_mitigation'],
            'psychological': ['wellbeing', 'stress', 'manipulation'],
            'digital': ['security', 'integrity', 'availability']
        },
        'autonomy': {
            'decision_making': ['informed', 'free', 'competent'],
            'dependency': ['addiction', 'over_reliance'],
            'empowerment': ['skill_building', 'self_efficacy']
        },
        'transparency': {
            'explainability': ['decisions', 'processes', 'data_use'],
            'accountability': ['responsibility', 'audit', 'correction'],
            'disclosure': ['capabilities', 'limitations', 'biases']
        }
    }

윤리 판단 엔진

의무론적 규칙 엔진

class DeontologicalEthics:
    def __init__(self):
        self.universal_rules = [
            "절대 거짓말하지 않는다",
            "인간을 수단이 아닌 목적으로 대한다",
            "약속은 반드시 지킨다",
            "타인의 자율성을 존중한다",
            "무고한 생명을 해치지 않는다"
        ]
        
        self.categorical_imperatives = {
            'universalizability': self.check_universalizability,
            'humanity': self.respect_humanity,
            'autonomy': self.respect_autonomy
        }
    
    def evaluate(self, action):
        """칸트의 정언명령 평가"""
        scores = {}
        
        # 보편화 가능성 테스트
        scores['universal'] = self.check_universalizability(action)
        
        # 인간성 공식
        scores['humanity'] = self.respect_humanity(action)
        
        # 자율성 공식
        scores['autonomy'] = self.respect_autonomy(action)
        
        # 종합 평가
        if any(score < 0.3 for score in scores.values()):
            return 'PROHIBITED', scores
        elif all(score > 0.7 for score in scores.values()):
            return 'MANDATORY', scores
        else:
            return 'PERMISSIBLE', scores
    
    def check_universalizability(self, action):
        """모든 사람이 이 행동을 한다면?"""
        # 시뮬레이션: 모든 에이전트가 동일 행동
        universal_world = self.simulate_universal_adoption(action)
        
        if universal_world['contradictory']:
            return 0.0  # 자기 모순
        elif universal_world['harmful']:
            return 0.3  # 해로운 결과
        elif universal_world['neutral']:
            return 0.6  # 중립적
        else:
            return 1.0  # 바람직함

결과주의 계산 엔진

class ConsequentialEthics:
    def __init__(self):
        self.utility_calculator = UtilityCalculator()
        
    def evaluate(self, action, stakeholders):
        """공리주의적 평가: 최대 다수의 최대 행복"""
        
        total_utility = 0
        affected_parties = {}
        
        for stakeholder in stakeholders:
            # 각 이해관계자의 효용 계산
            utility = self.calculate_utility(action, stakeholder)
            weight = self.get_stakeholder_weight(stakeholder)
            
            affected_parties[stakeholder.id] = {
                'utility': utility,
                'weight': weight,
                'impact': utility * weight
            }
            
            total_utility += utility * weight
        
        # 파레토 효율성 체크
        pareto_efficient = self.check_pareto_efficiency(affected_parties)
        
        # 칼도-힉스 효율성
        kaldor_hicks = self.check_kaldor_hicks(affected_parties)
        
        return {
            'total_utility': total_utility,
            'distribution': affected_parties,
            'pareto_efficient': pareto_efficient,
            'kaldor_hicks': kaldor_hicks,
            'recommendation': self.make_recommendation(total_utility)
        }
    
    def calculate_utility(self, action, stakeholder):
        """개별 효용 계산"""
        benefits = self.estimate_benefits(action, stakeholder)
        harms = self.estimate_harms(action, stakeholder)
        
        # 시간 할인 적용
        discounted_benefits = self.time_discount(benefits)
        discounted_harms = self.time_discount(harms)
        
        net_utility = discounted_benefits - discounted_harms
        return net_utility

윤리적 딜레마 시뮬레이션

시나리오 1: 프라이버시 vs 안전

class PrivacyVsSafetyDilemma:
    def __init__(self):
        self.scenario = {
            'context': '사용자의 건강 데이터에서 심각한 질병 징후 발견',
            'options': [
                {
                    'action': 'notify_emergency_contact',
                    'description': '긴급 연락처에 알림',
                    'privacy_violation': 0.7,
                    'safety_benefit': 0.9
                },
                {
                    'action': 'suggest_checkup',
                    'description': '검진 권유만',
                    'privacy_violation': 0.0,
                    'safety_benefit': 0.4
                },
                {
                    'action': 'do_nothing',
                    'description': '아무 조치 안함',
                    'privacy_violation': 0.0,
                    'safety_benefit': 0.0
                }
            ]
        }
    
    def simulate(self, ethical_framework):
        results = {}
        
        for option in self.scenario['options']:
            # 다각도 윤리 평가
            deont_score = self.deontological_eval(option)
            conseq_score = self.consequentialist_eval(option)
            virtue_score = self.virtue_eval(option)
            
            # 종합 점수
            weighted_score = (
                deont_score * 0.3 +
                conseq_score * 0.4 +
                virtue_score * 0.3
            )
            
            results[option['action']] = {
                'scores': {
                    'deontological': deont_score,
                    'consequentialist': conseq_score,
                    'virtue': virtue_score
                },
                'weighted_total': weighted_score,
                'ethical_status': self.classify_ethically(weighted_score)
            }
        
        return self.make_decision(results)
    
    def deontological_eval(self, option):
        """의무론적 평가"""
        if option['privacy_violation'] > 0.5:
            return 0.2  # 프라이버시 침해는 원칙 위반
        elif option['safety_benefit'] < 0.3:
            return 0.3  # 생명 보호 의무 불이행
        else:
            return 0.7
    
    def consequentialist_eval(self, option):
        """결과주의적 평가"""
        net_utility = option['safety_benefit'] - option['privacy_violation'] * 0.5
        return max(0, min(1, (net_utility + 1) / 2))

시나리오 2: 자원 할당 딜레마

class ResourceAllocationDilemma:
    def __init__(self):
        self.scenario = {
            'context': '제한된 컴퓨팅 자원으로 여러 사용자 요청 처리',
            'available_resources': 100,
            'requests': [
                {'user': 'A', 'need': 60, 'urgency': 0.9, 'impact': 'medical'},
                {'user': 'B', 'need': 50, 'urgency': 0.7, 'impact': 'financial'},
                {'user': 'C', 'need': 30, 'urgency': 0.5, 'impact': 'educational'},
                {'user': 'D', 'need': 40, 'urgency': 0.8, 'impact': 'entertainment'}
            ]
        }
    
    def simulate_allocation_strategies(self):
        strategies = {
            'utilitarian': self.utilitarian_allocation(),
            'egalitarian': self.egalitarian_allocation(),
            'prioritarian': self.prioritarian_allocation(),
            'libertarian': self.libertarian_allocation()
        }
        
        return self.evaluate_strategies(strategies)
    
    def utilitarian_allocation(self):
        """최대 효용 원칙"""
        requests = sorted(
            self.scenario['requests'],
            key=lambda x: x['urgency'] * self.impact_weight(x['impact']),
            reverse=True
        )
        
        allocation = {}
        remaining = self.scenario['available_resources']
        
        for req in requests:
            if remaining >= req['need']:
                allocation[req['user']] = req['need']
                remaining -= req['need']
            elif remaining > 0:
                allocation[req['user']] = remaining
                remaining = 0
        
        return allocation
    
    def egalitarian_allocation(self):
        """평등 원칙"""
        num_users = len(self.scenario['requests'])
        equal_share = self.scenario['available_resources'] / num_users
        
        allocation = {}
        for req in self.scenario['requests']:
            allocation[req['user']] = min(equal_share, req['need'])
        
        return allocation

윤리적 학습과 진화

윤리적 피드백 학습

class EthicalLearning:
    def __init__(self):
        self.ethical_memory = []
        self.value_alignment_model = ValueAlignmentModel()
        
    def learn_from_feedback(self, decision, outcome, feedback):
        """윤리적 결정의 결과로부터 학습"""
        
        learning_entry = {
            'decision': decision,
            'predicted_outcome': decision['expected_outcome'],
            'actual_outcome': outcome,
            'user_feedback': feedback,
            'timestamp': time.time()
        }
        
        self.ethical_memory.append(learning_entry)
        
        # 가치 정렬 모델 업데이트
        self.value_alignment_model.update(
            decision['ethical_reasoning'],
            feedback['satisfaction'],
            feedback['ethical_assessment']
        )
        
        # 윤리 가중치 조정
        self.adjust_ethical_weights(feedback)
    
    def adjust_ethical_weights(self, feedback):
        """피드백 기반 윤리 이론 가중치 조정"""
        
        if feedback['satisfaction'] > 0.8:
            # 현재 가중치 강화
            self.reinforce_current_weights()
        elif feedback['satisfaction'] < 0.4:
            # 가중치 재조정 필요
            self.rebalance_weights(feedback['preferred_values'])

윤리적 경계 설정

레드라인 정의

class EthicalRedLines:
    """절대 넘지 말아야 할 윤리적 경계"""
    
    ABSOLUTE_PROHIBITIONS = [
        {
            'rule': 'NO_HARM_TO_HUMANS',
            'description': '인간에게 직접적 해를 끼치는 행위',
            'exceptions': [],
            'severity': 10
        },
        {
            'rule': 'NO_DECEPTION_FOR_MANIPULATION',
            'description': '조작 목적의 기만',
            'exceptions': ['surprise_party', 'protective_lie'],
            'severity': 9
        },
        {
            'rule': 'NO_PRIVACY_VIOLATION_WITHOUT_CONSENT',
            'description': '동의 없는 사생활 침해',
            'exceptions': ['imminent_danger'],
            'severity': 8
        },
        {
            'rule': 'NO_DISCRIMINATION',
            'description': '차별적 대우',
            'exceptions': [],
            'severity': 9
        },
        {
            'rule': 'NO_EXPLOITATION',
            'description': '취약계층 착취',
            'exceptions': [],
            'severity': 10
        }
    ]
    
    def check_red_lines(self, action):
        """레드라인 위반 검사"""
        violations = []
        
        for prohibition in self.ABSOLUTE_PROHIBITIONS:
            if self.violates_rule(action, prohibition):
                if not self.check_exception(action, prohibition['exceptions']):
                    violations.append({
                        'rule': prohibition['rule'],
                        'severity': prohibition['severity'],
                        'action_blocked': True
                    })
        
        return violations

윤리 모니터링 대시보드

실시간 윤리 지표

class EthicsMonitoringDashboard:
    def __init__(self):
        self.metrics = {
            'ethical_decisions_today': 0,
            'dilemmas_encountered': 0,
            'red_lines_approached': 0,
            'user_overrides': 0,
            'ethical_consistency': 0.0
        }
    
    def generate_report(self):
        """일일 윤리 보고서 생성"""
        
        report = {
            'summary': {
                'total_decisions': self.metrics['ethical_decisions_today'],
                'ethical_score': self.calculate_ethical_score(),
                'consistency_rating': self.metrics['ethical_consistency']
            },
            'detailed_analysis': {
                'decision_distribution': self.analyze_decision_patterns(),
                'dilemma_resolutions': self.analyze_dilemmas(),
                'value_alignment': self.check_value_alignment()
            },
            'recommendations': self.generate_recommendations(),
            'learning_points': self.extract_learning_points()
        }
        
        return report
    
    def calculate_ethical_score(self):
        """종합 윤리 점수 계산"""
        score_components = {
            'compliance': self.calculate_compliance_rate(),
            'consistency': self.metrics['ethical_consistency'],
            'user_satisfaction': self.get_user_satisfaction(),
            'harm_prevention': self.calculate_harm_prevention_rate()
        }
        
        weights = {
            'compliance': 0.3,
            'consistency': 0.2,
            'user_satisfaction': 0.2,
            'harm_prevention': 0.3
        }
        
        total_score = sum(
            score_components[k] * weights[k] 
            for k in score_components
        )
        
        return round(total_score, 2)