본문으로 건너뛰기

P2 가설 정교화 - 구현 가이드

1. 개요

목적: P1에서 수집한 데이터와 사용자 답변을 바탕으로 불면증의 근본 원인에 대한 가설을 세우고 검증합니다.

트리거 조건:

  • P1 질문에 대한 사용자 답변 완료
  • 또는 Day 10 자동 진행 (답변 없을 시)

결과물:

  1. 불면증 원인 가설 (Primary, Secondary)
  2. 가설 검증 데이터
  3. 치료 우선순위 결정

2. 필요한 MCP 도구

2.1 Learning Tools

// 학습 패턴 분석
- getLearningHistory
입력: userId, startDate, endDate
출력: 레슨별 완료 상태, 소요 시간, 중단 패턴

- analyzeLearningDropout
입력: userId
출력: 중단 패턴, 재참여 시점, 중단 이유 추정

2.2 Questionnaire Tools

// 심리적 요인 분석
- getComorbidityAnalysis
입력: userId, roundNumber
출력: 우울-불안 동반, 스트레스-불면 연관성

- getBeliefBarriers
입력: userId
출력: 수면에 대한 비합리적 신념 목록

2.3 Agent Data Tools

// 패턴 인식
- identifyBehavioralPatterns
입력: userId, dateRange
출력: 야간 활동형, 불규칙 패턴 등

- correlateDomainData
입력: userId, domains[]
출력: 도메인 간 상관관계 분석

3. Flowise 플로우 구성

3.1 플로우 다이어그램

[P1 답변 수신] → [데이터 수집] → [패턴 분석] → [가설 생성] → [우선순위 결정]
↓ ↓ ↓
답변 파싱 MCP Tools Correlation

3.2 노드별 상세 설정

User Response Handler Node

Type: Webhook Receiver
Endpoint: /p1/responses
Validation:
- Check user answers completeness
- Parse structured responses
Output: userResponses

Pattern Analysis Node

Type: Custom MCP Chain
Tools:
- getLearningHistory
- analyzeLearningDropout
- identifyBehavioralPatterns
Analysis:
- Dropout patterns
- Activity distribution
- Engagement metrics

Hypothesis Generation Node

Type: LLM Chain
Model: gpt-4-turbo
System Prompt: |
불면증 원인 가설을 생성하는 전문가입니다.
다음 우선순위로 가설을 검증하세요:
1. 행동 패턴 (야간 활동, 불규칙성)
2. 심리적 요인 (우울, 불안, 스트레스)
3. 인지적 요인 (수면 신념)
4. 생활 습관 (카페인, 운동, 스크린)

Template: |
=== 사용자 데이터 ===
P1 답변: {{userResponses}}
학습 패턴: {{learningPatterns}}
심리 상태: {{psychologicalFactors}}

다음 형식으로 가설을 생성하세요:
{
"primary": "주요 원인",
"secondary": ["부차적 원인들"],
"confidence": 0.0-1.0,
"evidence": ["근거 데이터"],
"recommendedFocus": "치료 초점"
}

4. 가설 유형별 처리

4.1 행동 패턴 기반 가설

const behavioralHypothesis = {
"야간 활동형": {
indicators: [
learningPattern.preferredTimeOfDay === 'evening',
avgBedTime > 24.0, // 자정 이후
eveningActivityLevel > 0.7
],
treatment: "수면 위상 전진",
priority: "HIGH"
},

"불규칙 패턴": {
indicators: [
bedTimeVariance > 2.0, // 2시간 이상 변동
weekendJetlag > 1.5,
inconsistentSchedule: true
],
treatment: "수면 일정 안정화",
priority: "HIGH"
}
};

4.2 심리적 요인 가설

const psychologicalHypothesis = {
"우울 주도형": {
indicators: [
phq9Score >= 10,
earlyMorningAwakening: true,
motivationLoss: true
],
treatment: "행동 활성화 + CBT-I",
priority: "CRITICAL"
},

"불안 주도형": {
indicators: [
gad7Score >= 10,
sleepOnsetDifficulty: true,
racingThoughts: true
],
treatment: "이완 기법 + 인지 재구성",
priority: "HIGH"
}
};

4.3 인지적 요인 가설

const cognitiveHypothesis = {
"수면 신념 장애": {
indicators: [
dbas16Score > 3.8,
catastrophicThinking: true,
performanceAnxiety: true
],
beliefs: [
"8시간은 자야 한다",
"못 자면 다음날 망한다",
"수면은 통제할 수 없다"
],
treatment: "인지 재구성 중심",
priority: "MEDIUM"
}
};

5. 구현 체크리스트

5.1 데이터 수집 및 전처리

  • P1 사용자 답변 파싱
  • 학습 이력 7-14일 데이터 수집
  • 설문 점수 및 세부 응답 분석
  • 수면 패턴 데이터 상관관계 분석

5.2 가설 생성 로직

  • 다중 가설 생성 (최소 3개)
  • 가설별 신뢰도 점수 계산
  • 근거 데이터 명시
  • 상충되는 가설 처리

5.3 우선순위 결정

  • CRITICAL/HIGH/MEDIUM/LOW 분류
  • 복합 요인 가중치 처리
  • 치료 가능성 평가

6. 테스트 시나리오

시나리오 1: 명확한 단일 원인

Given:
- 야간 학습 선호 (10PM-2AM)
- 정상 범위 심리 점수
- 규칙적인 야간 활동
Expected:
- Primary: "야간 활동형 수면 위상 지연"
- Confidence: > 0.8
- Treatment: "점진적 수면 위상 전진"

시나리오 2: 복합 요인

Given:
- PHQ-9: 15점 (중등도 우울)
- 불규칙한 수면 패턴
- 수면 신념 문제
Expected:
- Primary: "우울 관련 불면증"
- Secondary: ["수면 일정 불규칙", "인지적 왜곡"]
- Confidence: 0.6-0.7
- Treatment: "통합적 접근 필요"

7. 출력 예시

{
"hypotheses": {
"primary": {
"type": "depression_induced_insomnia",
"description": "우울증상이 불면증을 유발하는 패턴",
"confidence": 0.75,
"evidence": [
"PHQ-9 12점 (중등도 우울)",
"새벽 조기 각성 패턴",
"학습 참여도 25% (동기 저하)"
]
},
"secondary": [
{
"type": "circadian_rhythm_disorder",
"description": "야간 활동 선호로 인한 수면 위상 지연",
"confidence": 0.60
},
{
"type": "cognitive_distortion",
"description": "수면에 대한 비합리적 신념",
"confidence": 0.55
}
]
},
"treatmentPriorities": {
"immediate": ["mood_support", "motivation_enhancement"],
"primary": ["behavioral_activation", "sleep_scheduling"],
"supportive": ["cognitive_restructuring", "relaxation"]
},
"nextSteps": {
"p3Config": {
"intensity": "moderate",
"primaryModule": "integrated_cbt",
"checkInFrequency": "daily"
}
}
}

8. 트러블슈팅

문제: 상충되는 가설

증상: 여러 가설이 비슷한 신뢰도
해결:
1. 추가 데이터 포인트 수집
2. 가중 평균 사용
3. 통합적 접근 채택

문제: 데이터 부족

증상: 가설 신뢰도 < 0.5
해결:
1. P1 추가 질문 생성
2. 기본 가설 템플릿 사용
3. P3에서 적응형 조정

9. 다음 단계 (P3 연동)

P2의 출력은 P3 치료 로드맵 설계의 핵심 입력이 됩니다:

// P2 → P3 데이터 전달
interface P2Output {
hypotheses: Hypothesis[];
treatmentPriorities: string[];
recommendedIntensity: 'gentle' | 'moderate' | 'intensive';
specialConsiderations: string[];
}

// P3에서 활용
const p3Config = {
primaryModule: selectModule(p2Output.hypotheses.primary.type),
intensity: p2Output.recommendedIntensity,
adaptations: mapHypothesesToAdaptations(p2Output.hypotheses)
};

10. 참고 자료