58 lines
2.6 KiB
Python
58 lines
2.6 KiB
Python
from ..repositories.ai_model_repository import AiModelRepository
|
|
from ..models import AiModel
|
|
from typing import Optional, List
|
|
import requests
|
|
from django.conf import settings # ใช้สำหรับ Configs ภายนอก/Secrets
|
|
|
|
class ConnectionError(Exception):
|
|
"""Custom Exception สำหรับการเชื่อมต่อล้มเหลว"""
|
|
pass
|
|
|
|
class AiModelService:
|
|
def __init__(self, repository: AiModelRepository):
|
|
self.repo = repository
|
|
|
|
def get_all_models(self) -> List[AiModel]:
|
|
return self.repo.get_all()
|
|
|
|
def create_model(self, validated_data: dict) -> AiModel:
|
|
# Business Logic: ตรวจสอบความซ้ำซ้อน, การตั้งค่าเริ่มต้น
|
|
new_model = AiModel(**validated_data)
|
|
return self.repo.save(new_model)
|
|
|
|
def test_connection(self, pk: int) -> dict:
|
|
"""Logic สำหรับเรียก HTTP Ping ไปยัง AI Service ภายนอก"""
|
|
model = self.repo.get_by_id(pk)
|
|
if not model:
|
|
raise ValueError("Model not found")
|
|
|
|
# ใช้ Root URL ของ Service สำหรับ Ping
|
|
test_url = model.base_url.rstrip('/') + '/'
|
|
|
|
try:
|
|
# ใช้ requests เพื่อเรียก HTTP (ใช้ httpx ถ้าต้องการ Async)
|
|
response = requests.get(test_url, timeout=5)
|
|
response.raise_for_status() # Raise error for 4xx or 5xx
|
|
|
|
return {
|
|
"status": "success",
|
|
"message": f"Successfully pinged {test_url}",
|
|
"response_status": response.status_code,
|
|
"response_data": response.json()
|
|
}
|
|
except requests.exceptions.RequestException as e:
|
|
# แปลง HTTP Error เป็น Custom Exception ของ Business Logic
|
|
raise ConnectionError(f"Connection failed to {test_url}: {e}")
|
|
|
|
def set_status(self, pk: int, new_status: str) -> Optional[AiModel]:
|
|
# Business Logic: การเปลี่ยนสถานะต้องผ่าน Service
|
|
model = self.repo.get_by_id(pk)
|
|
if model:
|
|
# Logic: มีเงื่อนไขว่าต้องผ่าน TESTING ก่อนไป ACTIVE
|
|
if model.status == 'TESTING' and new_status == 'ACTIVE':
|
|
# Logic: Trigger Hot Swap ใน FastAPI Service ก่อนเปลี่ยนสถานะ (ถ้าต้องการ)
|
|
pass
|
|
|
|
model.status = new_status
|
|
return self.repo.save(model)
|
|
return None |