diff --git a/ai-python/API-DOCUMENTATION.md b/ai-python/API-DOCUMENTATION.md new file mode 100644 index 0000000..ca78f2b --- /dev/null +++ b/ai-python/API-DOCUMENTATION.md @@ -0,0 +1,250 @@ +# AI Service API Documentation + +## 서비스 정보 +- **Base URL**: `http://localhost:8087` +- **프로덕션 URL**: `http://{AKS-IP}:8087` (배포 후) +- **포트**: 8087 +- **프로토콜**: HTTP +- **CORS**: 모든 origin 허용 (개발 환경) + +## API 엔드포인트 + +### 1. 실시간 AI 제안사항 스트리밍 (SSE) + +**엔드포인트**: `GET /api/v1/ai/suggestions/meetings/{meeting_id}/stream` + +**설명**: 회의 중 실시간으로 AI 제안사항을 Server-Sent Events로 스트리밍합니다. + +**파라미터**: +| 이름 | 위치 | 타입 | 필수 | 설명 | +|------|------|------|------|------| +| meeting_id | path | string | O | 회의 ID | + +**응답 형식**: `text/event-stream` + +**SSE 이벤트 구조**: +``` +event: ai-suggestion +id: 15 +data: {"suggestions":[{"id":"uuid","content":"제안 내용","timestamp":"14:23:45","confidence":0.92}]} +``` + +**응답 데이터 스키마**: +```typescript +interface SimpleSuggestion { + id: string; // 제안 ID (UUID) + content: string; // 제안 내용 (1-2문장) + timestamp: string; // 타임스탬프 (HH:MM:SS) + confidence: number; // 신뢰도 (0.0 ~ 1.0) +} + +interface RealtimeSuggestionsResponse { + suggestions: SimpleSuggestion[]; +} +``` + +**프론트엔드 연동 예시 (JavaScript/TypeScript)**: + +```javascript +// EventSource 연결 +const meetingId = 'meeting-123'; +const eventSource = new EventSource( + `http://localhost:8087/api/v1/ai/suggestions/meetings/${meetingId}/stream` +); + +// AI 제안사항 수신 +eventSource.addEventListener('ai-suggestion', (event) => { + const data = JSON.parse(event.data); + + data.suggestions.forEach(suggestion => { + console.log('새 제안:', suggestion.content); + console.log('신뢰도:', suggestion.confidence); + console.log('시간:', suggestion.timestamp); + + // UI 업데이트 + addSuggestionToUI(suggestion); + }); +}); + +// 에러 핸들링 +eventSource.onerror = (error) => { + console.error('SSE 연결 오류:', error); + eventSource.close(); +}; + +// 연결 종료 (회의 종료 시) +function closeSuggestions() { + eventSource.close(); +} +``` + +**React 예시**: + +```tsx +import { useEffect, useState } from 'react'; + +interface Suggestion { + id: string; + content: string; + timestamp: string; + confidence: number; +} + +function MeetingRoom({ meetingId }: { meetingId: string }) { + const [suggestions, setSuggestions] = useState([]); + + useEffect(() => { + const eventSource = new EventSource( + `http://localhost:8087/api/v1/ai/suggestions/meetings/${meetingId}/stream` + ); + + eventSource.addEventListener('ai-suggestion', (event) => { + const data = JSON.parse(event.data); + setSuggestions(prev => [...prev, ...data.suggestions]); + }); + + eventSource.onerror = () => { + console.error('SSE 연결 오류'); + eventSource.close(); + }; + + return () => { + eventSource.close(); + }; + }, [meetingId]); + + return ( +
+

AI 제안사항

+ {suggestions.map(s => ( +
+ {s.timestamp} +

{s.content}

+ 신뢰도: {(s.confidence * 100).toFixed(0)}% +
+ ))} +
+ ); +} +``` + +### 2. 헬스 체크 + +**엔드포인트**: `GET /health` + +**설명**: 서비스 상태 확인 (Kubernetes probe용) + +**응답 예시**: +```json +{ + "status": "healthy", + "service": "AI Service", + "port": 8087 +} +``` + +### 3. 서비스 정보 + +**엔드포인트**: `GET /` + +**설명**: 서비스 기본 정보 조회 + +**응답 예시**: +```json +{ + "service": "AI Service", + "version": "1.0.0", + "status": "running", + "endpoints": { + "test": "/api/v1/ai/suggestions/test", + "stream": "/api/v1/ai/suggestions/meetings/{meeting_id}/stream" + } +} +``` + +## 동작 흐름 + +``` +1. 회의 시작 + └─> 프론트엔드가 SSE 연결 시작 + +2. 음성 녹음 + └─> STT 서비스가 텍스트 변환 + └─> Event Hub 발행 + └─> AI 서비스가 Redis에 축적 + +3. 실시간 분석 (5초마다) + └─> Redis에서 텍스트 조회 + └─> 임계값(10개 세그먼트) 도달 시 + └─> Claude API 분석 + └─> SSE로 제안사항 전송 + └─> 프론트엔드 UI 업데이트 + +4. 회의 종료 + └─> SSE 연결 종료 +``` + +## 주의사항 + +1. **연결 유지**: + - SSE 연결은 장시간 유지되므로 네트워크 타임아웃 설정 필요 + - 브라우저는 연결 끊김 시 자동 재연결 시도 + +2. **CORS**: + - 개발 환경: 모든 origin 허용 + - 프로덕션: 특정 도메인만 허용하도록 설정 필요 + +3. **에러 처리**: + - SSE 연결 실패 시 재시도 로직 구현 권장 + - 네트워크 오류 시 사용자에게 알림 + +4. **성능**: + - 한 회의당 하나의 SSE 연결만 유지 + - 불필요한 재연결 방지 + +## 테스트 + +### curl 테스트: +```bash +# 헬스 체크 +curl http://localhost:8087/health + +# SSE 스트리밍 테스트 +curl -N http://localhost:8087/api/v1/ai/suggestions/meetings/test-meeting/stream +``` + +### 브라우저 테스트: +1. 서비스 실행: `python3 main.py` +2. Swagger UI 접속: http://localhost:8087/docs +3. `/api/v1/ai/suggestions/meetings/{meeting_id}/stream` 엔드포인트 테스트 + +## 환경 변수 + +프론트엔드에서 API URL을 환경 변수로 관리: + +```env +# .env.local +NEXT_PUBLIC_AI_SERVICE_URL=http://localhost:8087 +``` + +```typescript +const AI_SERVICE_URL = process.env.NEXT_PUBLIC_AI_SERVICE_URL || 'http://localhost:8087'; + +const eventSource = new EventSource( + `${AI_SERVICE_URL}/api/v1/ai/suggestions/meetings/${meetingId}/stream` +); +``` + +## FAQ + +**Q: SSE vs WebSocket?** +A: SSE는 서버→클라이언트 단방향 통신에 최적화되어 있습니다. 이 서비스는 AI 제안사항을 프론트엔드로 전송만 하므로 SSE가 적합합니다. + +**Q: 재연결은 어떻게?** +A: 브라우저의 EventSource는 자동으로 재연결을 시도합니다. 추가 로직 불필요. + +**Q: 여러 클라이언트가 동시 연결 가능?** +A: 네, 각 클라이언트는 독립적으로 SSE 연결을 유지합니다. + +**Q: 제안사항이 오지 않으면?** +A: Redis에 충분한 텍스트(10개 세그먼트)가 축적되어야 분석이 시작됩니다. 5초마다 체크합니다. diff --git a/ai-python/app/api/v1/suggestions.py b/ai-python/app/api/v1/suggestions.py index 4debf16..118cc88 100644 --- a/ai-python/app/api/v1/suggestions.py +++ b/ai-python/app/api/v1/suggestions.py @@ -17,7 +17,61 @@ settings = get_settings() claude_service = ClaudeService() -@router.get("/meetings/{meeting_id}/stream") +@router.get( + "/meetings/{meeting_id}/stream", + summary="실시간 AI 제안사항 스트리밍", + description=""" + 회의 중 실시간으로 AI 제안사항을 Server-Sent Events(SSE)로 스트리밍합니다. + + ### 동작 방식 + 1. Redis에서 누적된 회의 텍스트 조회 (5초마다) + 2. 임계값(10개 세그먼트) 이상이면 Claude API로 분석 + 3. 분석 결과를 SSE 이벤트로 전송 + + ### SSE 이벤트 형식 + ``` + event: ai-suggestion + id: {segment_count} + data: {"suggestions": [...]} + ``` + + ### 클라이언트 연결 예시 (JavaScript) + ```javascript + const eventSource = new EventSource( + 'http://localhost:8087/api/v1/ai/suggestions/meetings/{meeting_id}/stream' + ); + + eventSource.addEventListener('ai-suggestion', (event) => { + const data = JSON.parse(event.data); + console.log('새로운 제안사항:', data.suggestions); + }); + + eventSource.onerror = (error) => { + console.error('SSE 오류:', error); + eventSource.close(); + }; + ``` + + ### 주의사항 + - 연결은 클라이언트가 종료할 때까지 유지됩니다 + - 네트워크 타임아웃 설정이 충분히 길어야 합니다 + - 브라우저는 자동으로 재연결을 시도합니다 + """, + responses={ + 200: { + "description": "SSE 스트림 연결 성공", + "content": { + "text/event-stream": { + "example": """event: ai-suggestion +id: 15 +data: {"suggestions":[{"id":"550e8400-e29b-41d4-a716-446655440000","content":"신제품의 타겟 고객층을 20-30대로 설정하고, 모바일 우선 전략을 취하기로 논의 중입니다.","timestamp":"14:23:45","confidence":0.92}]} + +""" + } + } + } + } +) async def stream_ai_suggestions(meeting_id: str): """ 실시간 AI 제안사항 SSE 스트리밍 diff --git a/ai-python/app/config.py b/ai-python/app/config.py new file mode 100644 index 0000000..e39b502 --- /dev/null +++ b/ai-python/app/config.py @@ -0,0 +1,47 @@ +"""환경 설정""" +from pydantic_settings import BaseSettings +from functools import lru_cache + + +class Settings(BaseSettings): + """애플리케이션 설정""" + + # 서버 설정 + app_name: str = "AI Service" + host: str = "0.0.0.0" + port: int = 8087 + log_level: str = "INFO" + + # Claude API + claude_api_key: str = "" + claude_model: str = "claude-3-5-sonnet-20241022" + claude_max_tokens: int = 2000 + claude_temperature: float = 0.3 + + # Redis + redis_host: str = "20.249.177.114" + redis_port: int = 6379 + redis_password: str = "Hi5Jessica!" + redis_db: int = 4 + + # Event Hub + eventhub_connection_string: str = "" + eventhub_name: str = "hgzero-eventhub-name" + eventhub_consumer_group: str = "$Default" + + # AI 분석 설정 + min_segments_for_analysis: int = 10 + redis_ttl_seconds: int = 300 # 5분 + + # CORS + cors_origins: list = ["*"] + + class Config: + env_file = ".env" + case_sensitive = False + + +@lru_cache() +def get_settings() -> Settings: + """설정 싱글톤""" + return Settings() diff --git a/ai-python/main.py b/ai-python/main.py index 73169f3..e1fc02c 100644 --- a/ai-python/main.py +++ b/ai-python/main.py @@ -42,8 +42,34 @@ async def lifespan(app: FastAPI): app = FastAPI( title=settings.app_name, version="1.0.0", - description="실시간 AI 제안사항 서비스 (Python)", - lifespan=lifespan + description=""" + ## 실시간 AI 제안사항 서비스 (Python) + + 회의 중 실시간으로 텍스트를 분석하여 AI 제안사항을 생성하고 SSE(Server-Sent Events)로 스트리밍합니다. + + ### 주요 기능 + - 🎯 실시간 회의 분석 + - 🤖 Claude AI 기반 제안사항 생성 + - 📡 SSE 스트리밍 + - ⚡ Redis 캐시 연동 + + ### 인증 + 현재 버전은 인증이 필요하지 않습니다. + """, + lifespan=lifespan, + docs_url="/swagger-ui.html", # Spring Boot 스타일 + redoc_url="/redoc", + openapi_url="/v3/api-docs", # Spring Boot 스타일 OpenAPI JSON + openapi_tags=[ + { + "name": "AI Suggestions", + "description": "AI 제안사항 실시간 스트리밍 API" + }, + { + "name": "Health", + "description": "서비스 상태 확인" + } + ] ) # CORS 설정 (개발 환경: 모든 origin 허용) @@ -77,12 +103,17 @@ async def root(): } -@app.get("/health") +@app.get("/health", tags=["Health"]) async def health_check(): - """헬스 체크""" + """ + 헬스 체크 엔드포인트 + + Kubernetes liveness/readiness probe에서 사용 + """ return { "status": "healthy", - "service": settings.app_name + "service": settings.app_name, + "port": settings.port }