구조화된 예측 응답 반환

FastAPI로 AI 프로덕션 배포하기

Matt Eckerle

Software and Data Engineering Leader

모델 배포 시 과제

FastAPI를 사용한 ML 예측 흐름도

 

 

  1. 입력 데이터 적절히 수신
  2. 입력 데이터 유효성 검사 및 오류 처리
  3. 예측 수행
  4. 구조화된 응답 반환
FastAPI로 AI 프로덕션 배포하기

요청 구조 정의

from pydantic import BaseModel
class PredictionRequest(BaseModel):
    text: str
class PredictionResponse(BaseModel):

text: str
sentiment: str
confidence: float
FastAPI로 AI 프로덕션 배포하기

예측 엔드포인트 생성

@app.post("/predict")
def predict_sentiment(request: PredictionRequest):
    if sentiment_model is None:
        raise HTTPException(
            status_code=503,
            detail="Model not loaded"
        )

result = sentiment_model(request.text)
return PredictionResponse( text=request.text, sentiment=result[0]["label"], confidence=result[0]["score"] )

입력 JSON:

{"text": "This movie was fantastic!"}

 

응답:

{
    "text": "This movie was fantastic!",
    "sentiment": "POSITIVE",
    "confidence": 0.95
}
FastAPI로 AI 프로덕션 배포하기

오류 처리

try:
  result = sentiment_model(request.text)
  return PredictionResponse(
        text=request.text,
        sentiment=result[0]["label"],
        confidence=result[0]["score"]
    )
except Exception:
  raise HTTPException(
        status_code=500,
        detail="Prediction failed"
    )

모델 예측 실패 시 응답

{
    "detail": "Prediction failed",
    "status_code": 500
}
FastAPI로 AI 프로덕션 배포하기

엔드포인트 테스트

# Example request
import requests

response = requests.post(
    "http://localhost:8000/predict",
    json={"text": "Great product!"}
)
print(response.json())
{
    "text": "Great product!",
    "sentiment": "POSITIVE",
    "confidence": 0.998
}
FastAPI로 AI 프로덕션 배포하기

연습해 봅시다!

FastAPI로 AI 프로덕션 배포하기

Preparing Video For Download...