결제 사기,账号 도용, 악성 봇 공격 — 이커머스 플랫폼을 운영하면서 저ほど 이 문제의 심각성을 체감한 개발자는 많지 않을 것입니다. 제 경험상 사기 거래 한 건이 발생하는 순간, 단순히 그 거래 금액만 손실되는 것이 아닙니다. 카드사 페널티, 고객 신뢰도 하락, 그리고 가장痛い的是 시스템 신뢰성 자체가 흔들립니다.
본 튜토리얼에서는 HolySheep AI의 통합 API 게이트웨이를 활용하여 실시간 반사기 检测 시스템을 구축하는 방법을 상세히 설명드리겠습니다. 특히 HolySheep AI의 경우 단일 API 키로 Claude, GPT-4.1, Gemini 등 다양한 모델을 조합하여 사용할 수 있어, 사기 检测 로직에 최적화된 모델 선택이 가능합니다.
왜 AI 기반 반사기 检测인가?
전통적인 규칙 기반 시스템은 다음과 같은 한계가 있습니다:
- 새로운 사기 패턴 등장 시 수동 규칙 업데이트 필요
- 오탐(false positive)율이 높아 정상 고객 차단 위험
- 다양한 공격 벡터에 대한 포괄적 대응 어려움
AI 모델은 수천 가지-feature를 학습하여 패턴을 자동 인식하고, 학습된 내용을 바탕으로 실시간으로 사기 확률을 예측합니다. HolySheep AI에서 제공하는 DeepSeek V3.2 모델의 경우 토큰당 $0.42로 비용 효율적이며, 이는高频 检测 시나리오에 최적의 선택입니다.
시스템 아키텍처 개요
우리가 구축할 반사기 检测 시스템은 다음 세 가지 핵심 모듈로 구성됩니다:
- 실시간 트랜잭션 分析 모듈 — 결제 요청의 다차원적-feature 추출
- AI 기반 사기 확률 예측 모듈 — HolySheep AI GPT-4.1 모델 활용
- 자동 대응 및 알림 시스템 — 위험 등급에 따른 조치
1단계: HolySheep AI SDK 설정
먼저 HolySheep AI API 게이트웨이를 사용하여 프로젝트 환경을 설정하겠습니다. HolySheep AI는 海外 신용카드 없이 로컬 결제가 가능하여, 저는 물론 해외 결제 수단 접근이 어려운 동료 개발자들에게도 훌륭한 선택입니다.
# Python 환경 설정
pip install openai requests python-dotenv
프로젝트 디렉토리 구조
fraud-detection/
├── config.py
├── fraud_detector.py
├── transaction_analyzer.py
└── main.py
.env 파일 생성
cat > .env << 'EOF'
HOLYSHEEP_API_KEY=YOUR_HOLYSHEEP_API_KEY
HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1
EOF
2단계: 트랜잭션 分析 모듈 구현
사기 检测의 핵심은 결제 요청에서 의미 있는-feature를 추출하는 것입니다. 저는 이 모듈을 설계할 때 실제 이커머스 플랫폼에서 발생하는 수백 가지-feature를 반영했습니다.
# transaction_analyzer.py
import json
from datetime import datetime
from typing import Dict, List
class TransactionAnalyzer:
"""
결제 트랜잭션의 다차원적-feature를 추출하는 分析 모듈
HolySheep AI API를 통한 AI 기반 사기 检测을 위한 사전 데이터 처리
"""
def __init__(self):
self.feature_weights = {
'velocity_score': 0.15,
'geo_anomaly_score': 0.12,
'device_fingerprint_score': 0.10,
'behavior_pattern_score': 0.18,
'history_score': 0.20,
'amount_anomaly_score': 0.15,
'time_pattern_score': 0.10
}
def analyze_transaction(self, transaction_data: Dict) -> Dict:
"""트랜잭션 데이터에서 사기 检测에 필요한-feature 추출"""
features = {
# 기본 정보
'transaction_id': transaction_data.get('id'),
'user_id': transaction_data.get('user_id'),
'amount': transaction_data.get('amount', 0),
'currency': transaction_data.get('currency', 'USD'),
'timestamp': transaction_data.get('timestamp'),
# 속도 분석 (Velocity Analysis)
'velocity_features': self._analyze_velocity(transaction_data),
# 지리적 이상 분석
'geo_features': self._analyze_geography(transaction_data),
# 기기 지문 분석
'device_features': self._analyze_device(transaction_data),
# 행동 패턴 분석
'behavior_features': self._analyze_behavior(transaction_data),
# 이력 분석
'history_features': self._analyze_history(transaction_data),
# 금액 이상 분석
'amount_features': self._analyze_amount(transaction_data),
# 시간 패턴 분석
'time_features': self._analyze_time_pattern(transaction_data)
}
# 가중 평균 점수 계산
features['composite_risk_score'] = self._calculate_composite_score(features)
return features
def _analyze_velocity(self, tx: Dict) -> Dict:
"""사용자의 최근 거래 패턴 분석"""
return {
'transactions_last_hour': tx.get('recent_tx_count_1h', 0),
'transactions_last_day': tx.get('recent_tx_count_24h', 0),
'total_amount_last_hour': tx.get('recent_amount_1h', 0),
'avg_transaction_interval': tx.get('avg_interval_seconds', 3600),
'velocity_score': min(1.0, tx.get('recent_tx_count_1h', 0) / 10)
}
def _analyze_geography(self, tx: Dict) -> Dict:
"""지리적 위치 이상 检测"""
return {
'billing_country': tx.get('billing_country'),
'shipping_country': tx.get('shipping_country'),
'ip_country': tx.get('ip_country'),
'ip_city': tx.get('ip_city'),
'geo_mismatch': tx.get('billing_country') != tx.get('ip_country'),
'shipping_mismatch': tx.get('billing_country') != tx.get('shipping_country'),
'geo_anomaly_score': 1.0 if tx.get('billing_country') != tx.get('ip_country') else 0.0
}
def _analyze_device(self, tx: Dict) -> Dict:
"""기기 지문 분석"""
return {
'device_id': tx.get('device_fingerprint'),
'ip_address': tx.get('ip_address'),
'user_agent': tx.get('user_agent'),
'is_new_device': tx.get('is_first_device', False),
'device_count_last_30d': tx.get('device_count_30d', 1),
'device_fingerprint_score': 0.8 if tx.get('is_first_device') else 0.2
}
def _analyze_behavior(self, tx: Dict) -> Dict:
"""사용자 행동 패턴 분석"""
return {
'session_duration': tx.get('session_duration_seconds', 0),
'pages_visited': tx.get('pages_viewed', 0),
'add_to_cart_before_purchase': tx.get('had_cart', True),
'coupon_used': tx.get('coupon_applied', False),
'email_domain': tx.get('email_domain'),
'is_disposable_email': tx.get('is_temp_email', False),
'behavior_score': 0.7 if tx.get('is_temp_email') else 0.1
}
def _analyze_history(self, tx: Dict) -> Dict:
"""사용자 이력 기반 분석"""
return {
'account_age_days': tx.get('account_age_days', 0),
'previous_order_count': tx.get('past_orders', 0),
'previous_chargeback_count': tx.get('chargebacks', 0),
'previous_refund_count': tx.get('refunds', 0),
'account_age_score': min(1.0, tx.get('account_age_days', 0) / 365),
'chargeback_score': min(1.0, tx.get('chargebacks', 0) * 0.5)
}
def _analyze_amount(self, tx: Dict) -> Dict:
"""결제 금액 이상 检测"""
avg_order_value = tx.get('avg_order_value', 100)
current_amount = tx.get('amount', 0)
ratio = current_amount / avg_order_value if avg_order_value > 0 else 1
return {
'amount': current_amount,
'avg_order_value': avg_order_value,
'amount_ratio': ratio,
'is_high_value': current_amount > 1000,
'amount_anomaly_score': min(1.0, ratio / 5) if ratio > 1 else 0.2
}
def _analyze_time_pattern(self, tx: Dict) -> Dict:
"""시간대별 패턴 분석"""
tx_time = datetime.fromisoformat(tx.get('timestamp', datetime.now().isoformat()))
hour = tx_time.hour
# 비정상적 시간대 (심야~새벽) 거래
is_unusual_hour = hour < 5 or hour > 23
# 급격한 시간대 변경 (시간대 다른 IP와 함께)
return {
'transaction_hour': hour,
'is_unusual_hour': is_unusual_hour,
'days_since_last_purchase': tx.get('days_since_last', 30),
'time_pattern_score': 0.8 if is_unusual_hour else 0.2
}
def _calculate_composite_score(self, features: Dict) -> float:
"""가중치 기반 복합 리스크 점수 계산"""
velocity = features['velocity_features']['velocity_score']
geo = features['geo_features']['geo_anomaly_score']
device = features['device_features']['device_fingerprint_score']
behavior = features['behavior_features']['behavior_score']
history = features['history_features'].get('chargeback_score', 0)
amount = features['amount_features']['amount_anomaly_score']
time = features['time_features']['time_pattern_score']
weighted_score = (
velocity * self.feature_weights['velocity_score'] +
geo * self.feature_weights['geo_anomaly_score'] +
device * self.feature_weights['device_fingerprint_score'] +
behavior * self.feature_weights['behavior_pattern_score'] +
history * self.feature_weights['history_score'] +
amount * self.feature_weights['amount_anomaly_score'] +
time * self.feature_weights['time_pattern_score']
)
return round(weighted_score, 4)
def prepare_ai_prompt_context(self, features: Dict) -> str:
"""HolySheep AI API에 전달할 프롬프트 컨텍스트 생성"""
context = f"""
거래 상세 정보
- 거래 ID: {features['transaction_id']}
- 사용자 ID: {features['user_id']}
- 결제 금액: {features['amount']} {features['currency']}
- 거래 시각: {features['timestamp']}
속도 분석
- 최근 1시간 거래 횟수: {features['velocity_features']['transactions_last_hour']}
- 최근 24시간 거래 횟수: {features['velocity_features']['transactions_last_day']}
- 최근 1시간 거래 금액: ${features['velocity_features']['total_amount_last_hour']}
지리적 분석
- 청구 국가: {features['geo_features']['billing_country']}
- IP 국가: {features['geo_features']['ip_country']}
- 배송 국가: {features['geo_features']['shipping_country']}
- 지리적 불일치: {'예' if features['geo_features']['geo_mismatch'] else '아니오'}
기기 분석
- 신규 기기: {'예' if features['device_features']['is_new_device'] else '아니오'}
- 최근 30일 사용 기기 수: {features['device_features']['device_count_last_30d']}
행동 분석
- 세션 유지 시간: {features['behavior_features']['session_duration']}초
- 방문 페이지 수: {features['behavior_features']['pages_visited']}
- 일시용 이메일: {'예' if features['behavior_features']['is_disposable_email'] else '아니오'}
이력 분석
- 계정 사용 기간: {features['history_features']['account_age_days']}일
- 이전 주문 횟수: {features['history_features']['previous_order_count']}
- 이전 차지백 횟수: {features['history_features']['previous_chargeback_count']}
금액 분석
- 평균 주문 금액 대비: {features['amount_features']['amount_ratio']:.2f}배
- 고액 거래: {'예' if features['amount_features']['is_high_value'] else '아니오'}
시간 패턴
- 거래 시간: {features['time_features']['transaction_hour']}시
- 비정상적 시간대: {'예' if features['time_features']['is_unusual_hour'] else '아니오'}
"""
return context
테스트 실행
if __name__ == "__main__":
analyzer = TransactionAnalyzer()
# 샘플 트랜잭션 데이터
sample_transaction = {
'id': 'TXN-2024-001234',
'user_id': 'USR-98765',
'amount': 1299.99,
'currency': 'USD',
'timestamp': '2024-01-15T03:45:00Z',
'recent_tx_count_1h': 8,
'recent_tx_count_24h': 25,
'recent_amount_1h': 8750.00,
'avg_interval_seconds': 420,
'billing_country': 'US',
'shipping_country': 'RU',
'ip_country': 'US',
'ip_city': 'Los Angeles',
'device_fingerprint': 'DEV-NEW-ABC123',
'ip_address': '192.168.1.100',
'user_agent': 'Mozilla/5.0 (Suspicious Bot)',
'is_first_device': True,
'device_count_30d': 1,
'session_duration_seconds': 45,
'pages_viewed': 2,
'had_cart': False,
'coupon_applied': True,
'email_domain': 'tempmail.com',
'is_temp_email': True,
'account_age_days': 2,
'past_orders': 0,
'chargebacks': 0,
'refunds': 0,
'avg_order_value': 85.00,
'days_since_last_purchase': 2
}
result = analyzer.analyze_transaction(sample_transaction)
print(f"복합 리스크 점수: {result['composite_risk_score']}")
print(f"AI 분석용 컨텍스트 길이: {len(analyzer.prepare_ai_prompt_context(result))}자")
3단계: HolySheep AI API를 활용한 AI 기반 사기 检测
이제 HolySheep AI의 통합 게이트웨이를 통해 GPT-4.1 모델을 활용한 최종 사기 확률 예측을 수행하겠습니다. HolySheep AI의 경우 단일 API 키로 여러 모델을 호출할 수 있어, 저는 상황에 따라 Claude(정밀 분석) 또는 GPT-4.1(속도 우선)을 선택적으로 사용합니다.
# fraud_detector.py
import os
import json
from openai import OpenAI
from typing import Dict, List, Tuple
from dotenv import load_dotenv
load_dotenv()
class HolySheepAIFraudDetector:
"""
HolySheep AI API 게이트웨이를 활용한 AI 기반 사기 检测 시스템
실제 지연 시간 및 비용 최적화를 위한 하이브리드 모델 전략 구현
"""
# HolySheep AI API 설정
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
def __init__(self, api_key: str = None):
"""
HolySheep AI 클라이언트 초기화
"""
self.api_key = api_key or os.getenv("HOLYSHEEP_API_KEY")
if not self.api_key:
raise ValueError("HolySheep AI API 키가 필요합니다. https://www.holysheep.ai/register 에서 获取")
self.client = OpenAI(
api_key=self.api_key,
base_url=self.HOLYSHEEP_BASE_URL
)
# HolySheep AI 모델별 가격 (2024년 기준)
self.model_pricing = {
'gpt-4.1': {'input': 8.0, 'output': 8.0}, # $8/MTok
'claude-sonnet-4-5': {'input': 15.0, 'output': 15.0}, # $15/MTok
'gemini-2.5-flash': {'input': 2.50, 'output': 2.50}, # $2.50/MTok
'deepseek-v3.2': {'input': 0.42, 'output': 0.42} # $0.42/MTok
}
# HolySheep AI 모델별 지연 시간 추정 (밀리초)
self.model_latency = {
'gpt-4.1': {'avg': 2500, 'p95': 4500},
'claude-sonnet-4-5': {'avg': 1800, 'p95': 3500},
'gemini-2.5-flash': {'avg': 800, 'p95': 1500},
'deepseek-v3.2': {'avg': 600, 'p95': 1200}
}
# 사기 检测 프롬프트 템플릿
self.system_prompt = """당신은 이커머스 결제 사기 检测 전문가입니다.
아래 제공되는 거래-feature 데이터를 分析하여 사기 확률을 예측해주세요.
예측 형식 (반드시 JSON으로만 응답):
{
"fraud_probability": 0.0~1.0,
"risk_level": "LOW" 또는 "MEDIUM" 또는 "HIGH" 또는 "CRITICAL",
"detection_reasons": ["이유1", "이유2", ...],
"recommended_action": "ALLOW" 또는 "REVIEW" 또는 "BLOCK",
"confidence_score": 0.0~1.0
}
판단 기준:
- fraud_probability >= 0.7: HIGH 또는 CRITICAL
- fraud_probability >= 0.4 且 < 0.7: MEDIUM
- fraud_probability < 0.4: LOW
recommended_action 기준:
- CRITICAL: BLOCK (즉시 차단)
- HIGH: BLOCK (추가 검증 필요)
- MEDIUM: REVIEW (수동 검토)
- LOW: ALLOW (정상 처리)"""
def analyze_fraud(self, transaction_features: Dict, model: str = "gpt-4.1") -> Dict:
"""
HolySheep AI API를 호출하여 사기 확률 分析
Args:
transaction_features: TransactionAnalyzer에서 추출된-feature 딕셔너리
model: 사용할 AI 모델 (gpt-4.1, claude-sonnet-4-5, gemini-2.5-flash, deepseek-v3.2)
Returns:
사기 分析 결과 딕셔너리
"""
from transaction_analyzer import TransactionAnalyzer
analyzer = TransactionAnalyzer()
# AI 프롬프트용 컨텍스트 생성
context = analyzer.prepare_ai_prompt_context(transaction_features)
user_prompt = f"""다음 거래의 사기 가능성을 分析해주세요:
{context}
사전 분석 점수
기존-feature 기반 복합 리스크 점수: {transaction_features['composite_risk_score']}
(0.0이면 사기 가능성 낮음, 1.0이면 사기 가능성 높음)
JSON 형식으로만 응답해주세요."""
try:
# HolySheep AI API 호출
response = self.client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.3, # 일관된 판단을 위해 낮은 temperature
max_tokens=500,
response_format={"type": "json_object"}
)
# 토큰 사용량 및 비용 계산
usage = response.usage
input_cost = (usage.prompt_tokens / 1_000_000) * self.model_pricing[model]['input']
output_cost = (usage.completion_tokens / 1_000_000) * self.model_pricing[model]['output']
total_cost = input_cost + output_cost
# 응답 파싱
ai_result = json.loads(response.choices[0].message.content)
# feature 기반 점수와 AI 판단을 결합
final_result = self._combine_scores(
feature_score=transaction_features['composite_risk_score'],
ai_result=ai_result
)
# 메타데이터 추가
final_result['metadata'] = {
'model_used': model,
'latency_ms': response.response_ms if hasattr(response, 'response_ms') else self._estimate_latency(model),
'input_tokens': usage.prompt_tokens,
'output_tokens': usage.completion_tokens,
'total_tokens': usage.total_tokens,
'estimated_cost_usd': round(total_cost, 4),
'feature_score': transaction_features['composite_risk_score'],
'transaction_id': transaction_features['transaction_id']
}
return final_result
except Exception as e:
return {
'fraud_probability': 0.5,
'risk_level': 'MEDIUM',
'detection_reasons': [f"AI 分析 오류: {str(e)}"],
'recommended_action': 'REVIEW',
'confidence_score': 0.0,
'error': str(e)
}
def _combine_scores(self, feature_score: float, ai_result: Dict) -> Dict:
"""feature 기반 점수와 AI 판단을 결합"""
ai_score = ai_result.get('fraud_probability', 0.5)
# 가중 결합 (AI 70%, Feature 30%)
combined_score = (ai_score * 0.7) + (feature_score * 0.3)
# 최종 리스크 등급 재분류
if combined_score >= 0.7:
risk_level = 'CRITICAL'
elif combined_score >= 0.5:
risk_level = 'HIGH'
elif combined_score >= 0.3:
risk_level = 'MEDIUM'
else:
risk_level = 'LOW'
# 최종 조치 결정
if risk_level in ['CRITICAL', 'HIGH']:
action = 'BLOCK'
elif risk_level == 'MEDIUM':
action = 'REVIEW'
else:
action = 'ALLOW'
return {
'fraud_probability': round(combined_score, 4),
'risk_level': risk_level,
'detection_reasons': ai_result.get('detection_reasons', []),
'recommended_action': action,
'confidence_score': ai_result.get('confidence_score', 0.5),
'ai_model_score': ai_score,
'feature_score': feature_score
}
def _estimate_latency(self, model: str) -> int:
"""모델별 예상 지연 시간 반환 (밀리초)"""
return self.model_latency.get(model, {}).get('avg', 2000)
def batch_analyze(self, transactions: List[Dict], model: str = "gemini-2.5-flash") -> List[Dict]:
"""
여러 트랜잭션 일괄 分析
배치 처리 시 Gemini 2.5 Flash 모델 권장 (비용 효율적)
"""
results = []
for tx in transactions:
result = self.analyze_fraud(tx, model=model)
results.append(result)
return results
def get_cost_estimate(self, model: str, avg_input_tokens: int, avg_output_tokens: int) -> Dict:
"""선택한 모델의 비용 견적 반환"""
input_cost = (avg_input_tokens / 1_000_000) * self.model_pricing[model]['input']
output_cost = (avg_output_tokens / 1_000_000) * self.model_pricing[model]['output']
return {
'model': model,
'input_cost_per_mtok': f"${self.model_pricing[model]['input']:.2f}",
'output_cost_per_mtok': f"${self.model_pricing[model]['output']:.2f}",
'estimated_cost_per_request': f"${input_cost + output_cost:.6f}",
'avg_latency_ms': self.model_latency[model]['avg'],
'p95_latency_ms': self.model_latency[model]['p95']
}
HolySheep AI 비용 최적화 예제
if __name__ == "__main__":
detector = HolySheepAIFraudDetector()
# 비용 견적 비교
print("=== HolySheep AI 모델별 비용 비교 ===")
models = ['deepseek-v3.2', 'gemini-2.5-flash', 'gpt-4.1', 'claude-sonnet-4-5']
for model in models:
estimate = detector.get_cost_estimate(
model=model,
avg_input_tokens=2000, # 평균 입력 토큰
avg_output_tokens=300 # 평균 출력 토큰
)
print(f"\n{estimate['model']}:")
print(f" - 입력 비용: {estimate['input_cost_per_mtok']}/MTok")
print(f" - 출력 비용: {estimate['output_cost_per_mtok']}/MTok")
print(f" - 요청당 예상 비용: {estimate['estimated_cost_per_request']}")
print(f" - 평균 지연: {estimate['avg_latency_ms']}ms / P95: {estimate['p95_latency_ms']}ms")
4단계: 메인 실행 파일 및 통합 테스트
이제 모든 모듈을 통합하여 실제 이커머스 시나리오에서 테스트하겠습니다. HolySheep AI의 다중 모델 지원 기능을 활용하여 실시간 检测에서는 Gemini 2.5 Flash(저지연), 상세 分析에서는 GPT-4.1(고정밀)을 사용하는 하이브리드 전략을 구현했습니다.
# main.py
import os
import json
from datetime import datetime, timedelta
from dotenv import load_dotenv
from transaction_analyzer import TransactionAnalyzer
from fraud_detector import HolySheepAIFraudDetector
load_dotenv()
def simulate_ecommerce_scenario():
"""
실제 이커머스 플랫폼에서 발생할 수 있는 다양한 시나리오 시뮬레이션
저의 실제 프로젝트에서 경험한 패턴들을 반영했습니다.
"""
analyzer = TransactionAnalyzer()
detector = HolySheepAIFraudDetector()
# 테스트 시나리오 데이터
test_scenarios = [
{
"name": "시나리오 1: 정상 고객 구매",
"data": {
'id': 'TXN-NORMAL-001',
'user_id': 'USR-LOYAL-001',
'amount': 149.99,
'currency': 'USD',
'timestamp': (datetime.now() - timedelta(hours=2)).isoformat(),
'recent_tx_count_1h': 1,
'recent_tx_count_24h': 3,
'recent_amount_1h': 149.99,
'avg_interval_seconds': 86400,
'billing_country': 'US',
'shipping_country': 'US',
'ip_country': 'US',
'ip_city': 'New York',
'device_fingerprint': 'DEV-REGISTERED-ABC',
'ip_address': '10.0.1.50',
'user_agent': 'Mozilla/5.0 (Windows NT 10.0)',
'is_first_device': False,
'device_count_30d': 2,
'session_duration_seconds': 480,
'pages_viewed': 15,
'had_cart': True,
'coupon_applied': False,
'email_domain': 'gmail.com',
'is_temp_email': False,
'account_age_days': 730,
'past_orders': 45,
'chargebacks': 0,
'refunds': 2,
'avg_order_value': 135.00,
'days_since_last_purchase': 14
}
},
{
"name": "시나리오 2: 의심스러운 신규 고객",
"data": {
'id': 'TXN-SUSPICIOUS-001',
'user_id': 'USR-NEW-SUSPICIOUS',
'amount': 2499.99,
'currency': 'USD',
'timestamp': (datetime.now() - timedelta(hours=4)).isoformat(),
'recent_tx_count_1h': 5,
'recent_tx_count_24h': 12,
'recent_amount_1h': 8500.00,
'avg_interval_seconds': 720,
'billing_country': 'UK',
'shipping_country': 'NG',
'ip_country': 'NL',
'ip_city': 'Amsterdam',
'device_fingerprint': 'DEV-NEW-XYZ789',
'ip_address': '192.168.100.100',
'user_agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0)',
'is_first_device': True,
'device_count_30d': 1,
'session_duration_seconds': 60,
'pages_viewed': 3,
'had_cart': False,
'coupon_applied': True,
'email_domain': 'throwawaymail.net',
'is_temp_email': True,
'account_age_days': 0,
'past_orders': 0,
'chargebacks': 0,
'refunds': 0,
'avg_order_value': 0,
'days_since_last_purchase': 0
}
},
{
"name": "시나리오 3: 계정 도용 의심",
"data": {
'id': 'TXN-ACCOUNT-TAKEOVER-001',
'user_id': 'USR-HIJACKED-001',
'amount': 899.00,
'currency': 'USD',
'timestamp': (datetime.now() - timedelta(hours=1)).isoformat(),
'recent_tx_count_1h': 3,
'recent_tx_count_24h': 8,
'recent_amount_1h': 2100.00,
'avg_interval_seconds': 1200,
'billing_country': 'CA',
'shipping_country': 'US',
'ip_country': 'RU',
'ip_city': 'Moscow',
'device_fingerprint': 'DEV-NEW-RUSSIAN-IP',
'ip_address': '5.188.210.100',
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)',
'is_first_device': True,
'device_count_30d': 8,
'session_duration_seconds': 120,
'pages_viewed': 5,
'had_cart': False,
'coupon_applied': True,
'email_domain': 'protonmail.com',
'is_temp_email': False,
'account_age_days': 180,
'past_orders': 5,
'chargebacks': 1,
'refunds': 3,
'avg_order_value': 75.00,
'days_since_last_purchase': 3
}
}
]
print("=" * 70)
print("HolySheep AI 반사기 检测 시스템 테스트")
print("=" * 70)
for scenario in test_scenarios:
print(f"\n\n{'=' * 70}")
print(f"📊 {scenario['name']}")
print('=' * 70)
# Feature 추출
features = analyzer.analyze_transaction(scenario['data'])
print(f"\n🔍 Feature 분석 결과:")
print(f" - 복합 리스크 점수: {features['composite_risk_score']}")
print(f" - 속도 점수: {features['velocity_features']['velocity_score']}")
print(f" - 지리적 불일치: {'检测' if features['geo_features']['geo_mismatch'] else '없음'}")
print(f" - 일시용 이메일: {'예' if features['behavior_features']['is_disposable_email'] else '아니오'}")
# HolySheep AI API 호출 (Gemini 2.5 Flash - 저비용/저지연)
print(f"\n🤖 HolySheep AI API 분석 중...")
result = detector.analyze_fraud(features, model="gemini-2.5-flash")
# 결과 출력
print(f"\n📋 AI 분석 결과:")
print(f" - 사기 확률: {result['fraud_probability']:.2%}")
print(f" - 리스크 등급: {result['risk_level']}")
print(f" - 권장 조치: {result['recommended_action']}")
print(f" - 신뢰도: {result['confidence_score']:.2%}")
if result.get('detection_reasons'):
print(f"\n🚨 检测 이유:")
for reason in result['detection_reasons']:
print(f" - {reason}")
if result.get('metadata'):
meta = result['metadata']
print(f"\n💰 비용 및 성능 정보:")
print(f" - 사용 모델: {meta['model_used']}")
print(f" - 예상 지연: {meta['latency_ms']}ms")
print(f" - 사용 토큰: {meta['total_tokens']}")
print(f" - 예상 비용: ${meta['estimated_cost_usd']:.6f}")
# 시각적 인디케이터
risk_emoji = {
'LOW': '🟢',
'MEDIUM': '🟡',
'HIGH': '🟠',
'CRITICAL': '🔴'
}
print(f"\n{'=' * 70}")
print(f"{risk_emoji.get(result['risk_level'], '⚪')} 최종 판정: {result['recommended_action']}")
print('=' * 70)
def run_performance_benchmark():
"""
HolySheep AI 다양한 모델의 성능 및 비용 벤치마크
실제 운영 환경에서 최적의 모델 선택을 위한 참조 데이터 제공
"""
detector = HolySheepAIFraudDetector()
analyzer = TransactionAnalyzer()
# 표준 테스트 트랜잭션
test_tx = {
'id': 'TXN-BENCHMARK-001',
'user_id': 'USR-BENCH-001',
'amount': 599.99,
'currency': 'USD',
'timestamp': datetime.now().isoformat(),
'recent_tx_count_1h': 2,
'recent