# Hearth Chat과 Lily LLM API 연동 가이드
## 🔗 연동 개요
Hugging Face Spaces에 배포된 Lily LLM API를 Railway에서 호스팅되는 Hearth Chat 서비스와 연동하는 방법을 설명합니다.
## 1. Hugging Face Spaces 배포 완료 확인
### 1.1 API 엔드포인트 확인
배포된 Lily LLM API URL:
```
https://YOUR_USERNAME-lily-llm-api.hf.space
```
### 1.2 주요 엔드포인트 테스트
```bash
# 헬스 체크
curl https://YOUR_USERNAME-lily-llm-api.hf.space/health
# 모델 목록 확인
curl https://YOUR_USERNAME-lily-llm-api.hf.space/models
# 텍스트 생성 테스트
curl -X POST https://YOUR_USERNAME-lily-llm-api.hf.space/generate \
-F "prompt=안녕하세요! 테스트입니다."
```
## 2. Hearth Chat 설정 업데이트
### 2.1 AI 설정 모달 업데이트
`hearth_chat_react/src/components/AISettingsModal.js`에서 Lily LLM 설정 추가:
```javascript
// Lily LLM API URL 설정
{settings.aiProvider === 'lily' && (
<>
🌐 Hugging Face Spaces에서 호스팅
멀티모달 AI 모델 (텍스트 + 이미지 처리)
>
)}
```
### 2.2 연결 테스트 함수 업데이트
```javascript
case 'lily':
testUrl = `${settings.lilyApiUrl}/health`;
testData = {
method: 'GET',
headers: {
'Accept': 'application/json'
}
};
// 추가 생성 테스트
if (response.ok) {
const generateTestUrl = `${settings.lilyApiUrl}/generate`;
const generateResponse = await fetch(generateTestUrl, {
method: 'POST',
body: new FormData([
['prompt', '연결 테스트입니다.']
])
});
if (generateResponse.ok) {
const result = await generateResponse.json();
console.log('Lily LLM 생성 테스트 성공:', result);
}
}
break;
```
## 3. 백엔드 연동 업데이트
### 3.1 Consumers.py 수정
`hearth_chat_django/chat/consumers.py`에서 Lily LLM API 호출 부분:
```python
async def call_lily_api(user_message, user_emotion, image_urls=None, documents=None):
"""Lily LLM API 호출 (Hugging Face Spaces)"""
import requests
import aiohttp
try:
# 사용자 설정에서 API URL 가져오기
user = getattr(self, 'scope', {}).get('user', None)
ai_settings = None
if user and hasattr(user, 'is_authenticated') and user.is_authenticated:
ai_settings = await self.get_user_ai_settings(user)
# API URL 설정 (기본값: Hugging Face Spaces)
lily_api_url = ai_settings.get('lilyApiUrl', 'https://gbrabbit-lily-math-rag.hf.space') if ai_settings else 'https://gbrabbit-lily-math-rag.hf.space'
lily_model = ai_settings.get('lilyModel', 'kanana-1.5-v-3b-instruct') if ai_settings else 'kanana-1.5-v-3b-instruct'
# API 엔드포인트
generate_url = f"{lily_api_url}/generate"
# 요청 데이터 준비
data = {
'prompt': f"{emotion_prompt}\n\n사용자 메시지: {user_message}",
'max_length': 200,
'temperature': 0.7
}
files = {}
# 이미지 처리
if image_urls and len(image_urls) > 0:
print(f"🖼️ 이미지 처리: {len(image_urls)}개")
async with aiohttp.ClientSession() as session:
for i, image_url in enumerate(image_urls[:4]): # 최대 4개 이미지
try:
async with session.get(image_url) as img_response:
if img_response.status == 200:
image_data = await img_response.read()
files[f'image{i+1}'] = ('image.jpg', image_data, 'image/jpeg')
except Exception as e:
print(f"❌ 이미지 {i+1} 로드 실패: {e}")
# API 호출
timeout = aiohttp.ClientTimeout(total=120) # 2분 타임아웃
async with aiohttp.ClientSession(timeout=timeout) as session:
if files:
# 멀티파트 요청 (이미지 포함)
form_data = aiohttp.FormData()
for key, value in data.items():
form_data.add_field(key, str(value))
for key, (filename, file_data, content_type) in files.items():
form_data.add_field(key, file_data, filename=filename, content_type=content_type)
async with session.post(generate_url, data=form_data) as response:
if response.status == 200:
result = await response.json()
lily_response = result.get('generated_text', '죄송합니다. 응답을 생성할 수 없습니다.')
return {
"response": lily_response,
"provider": "lily",
"ai_name": "Lily LLM",
"ai_type": "huggingface"
}
else:
error_text = await response.text()
raise Exception(f"Lily API 오류: {response.status} - {error_text}")
else:
# 일반 POST 요청 (텍스트만)
async with session.post(generate_url, data=data) as response:
if response.status == 200:
result = await response.json()
lily_response = result.get('generated_text', '죄송합니다. 응답을 생성할 수 없습니다.')
return {
"response": lily_response,
"provider": "lily",
"ai_name": "Lily LLM",
"ai_type": "huggingface"
}
else:
error_text = await response.text()
raise Exception(f"Lily API 오류: {response.status} - {error_text}")
except Exception as e:
print(f"❌ Lily LLM API 호출 실패: {e}")
raise e
```
### 3.2 환경 변수 설정
Railway 환경에서 다음 환경 변수 추가:
```bash
# Lily LLM API 설정
LILY_LLM_API_URL=https://YOUR_USERNAME-lily-llm-api.hf.space
LILY_LLM_MODEL=kanana-1.5-v-3b-instruct
LILY_LLM_TIMEOUT=120
```
## 4. 테스트 및 검증
### 4.1 연동 테스트 스크립트
```python
# test_hearth_lily_integration.py
import requests
import json
def test_hearth_chat_lily_integration():
"""Hearth Chat과 Lily LLM 연동 테스트"""
# Hearth Chat API 엔드포인트 (Railway)
hearth_chat_url = "https://your-hearth-chat.railway.app"
# 1. 로그인 및 세션 획득
session = requests.Session()
# 2. AI 설정 업데이트
ai_settings = {
"aiProvider": "lily",
"lilyApiUrl": "https://YOUR_USERNAME-lily-llm-api.hf.space",
"lilyModel": "kanana-1.5-v-3b-instruct",
"aiEnabled": True
}
settings_response = session.patch(
f"{hearth_chat_url}/api/chat/user/settings/",
json=ai_settings
)
print(f"설정 업데이트: {settings_response.status_code}")
# 3. 채팅 테스트
test_messages = [
"안녕하세요! Lily LLM 테스트입니다.",
"오늘 날씨가 어떤가요?",
"간단한 수학 문제를 내주세요."
]
for message in test_messages:
print(f"\n📤 테스트 메시지: {message}")
# WebSocket 또는 HTTP API를 통한 메시지 전송
# (실제 구현에 따라 조정)
# 응답 확인
print(f"✅ 응답 받음")
if __name__ == "__main__":
test_hearth_chat_lily_integration()
```
### 4.2 이미지 처리 테스트
```python
def test_image_processing():
"""이미지 처리 연동 테스트"""
# 테스트 이미지 업로드
with open("test_image.jpg", "rb") as f:
files = {"image": f}
data = {"message": "이미지에서 무엇을 볼 수 있나요?"}
response = requests.post(
"https://your-hearth-chat.railway.app/api/chat/send-message/",
files=files,
data=data
)
print(f"이미지 처리 테스트: {response.status_code}")
print(f"응답: {response.json()}")
```
## 5. 모니터링 및 로그
### 5.1 Hugging Face Spaces 로그 모니터링
```bash
# Spaces 대시보드에서 실시간 로그 확인
# API 호출 빈도 및 응답 시간 모니터링
```
### 5.2 Railway 로그 모니터링
```bash
# Railway 대시보드에서 Hearth Chat 로그 확인
# Lily LLM API 호출 성공/실패 모니터링
```
## 6. 성능 최적화
### 6.1 캐싱 전략
```python
# Redis를 이용한 응답 캐싱
import redis
redis_client = redis.Redis(host='localhost', port=6379, db=0)
def cached_lily_response(prompt_hash, response):
"""응답 캐싱"""
redis_client.setex(f"lily_cache:{prompt_hash}", 3600, json.dumps(response))
def get_cached_response(prompt_hash):
"""캐시된 응답 조회"""
cached = redis_client.get(f"lily_cache:{prompt_hash}")
return json.loads(cached) if cached else None
```
### 6.2 로드 밸런싱
```python
# 여러 Hugging Face Spaces 인스턴스 사용
LILY_API_ENDPOINTS = [
"https://username1-lily-llm-api.hf.space",
"https://username2-lily-llm-api.hf.space"
]
def get_available_endpoint():
"""사용 가능한 엔드포인트 선택"""
for endpoint in LILY_API_ENDPOINTS:
try:
response = requests.get(f"{endpoint}/health", timeout=5)
if response.status_code == 200:
return endpoint
except:
continue
return LILY_API_ENDPOINTS[0] # 기본값
```
## 7. 보안 고려사항
### 7.1 API 키 관리
```python
# 환경 변수로 민감한 정보 관리
import os
LILY_API_KEY = os.getenv('LILY_API_KEY') # 필요시
LILY_API_SECRET = os.getenv('LILY_API_SECRET') # 필요시
```
### 7.2 요청 제한
```python
# 사용자별 요청 제한
from django.core.cache import cache
def check_rate_limit(user_id):
"""사용자별 요청 제한 확인"""
key = f"lily_api_rate_limit:{user_id}"
current = cache.get(key, 0)
if current >= 100: # 시간당 100회 제한
return False
cache.set(key, current + 1, 3600) # 1시간
return True
```
---
## 🎉 연동 완료
모든 설정이 완료되면:
1. **Hugging Face Spaces**: Lily LLM API 서버 호스팅
2. **Railway**: Hearth Chat 서비스 호스팅
3. **연동**: 두 서비스 간 원활한 통신
사용자는 Hearth Chat 인터페이스를 통해 Hugging Face에서 호스팅되는 강력한 Lily LLM AI를 사용할 수 있게 됩니다! 🚀