การโหลดโมเดลที่ผ่านการฝึกแล้ว

การ Deploy AI สู่ Production ด้วย FastAPI

Matt Eckerle

Software and Data Engineering Leader

โครงสร้างปัจจุบัน

ผังแสดงการพยากรณ์ด้วย ML ผ่าน FastAPI

การ Deploy AI สู่ Production ด้วย FastAPI

ปัญหาของการโหลดโมเดล

ผังอธิบายวงจร request/response

ชายผู้หงุดหงิดที่รอการตอบสนองจาก API

การ Deploy AI สู่ Production ด้วย FastAPI

โหลดโมเดลก่อนรับ request

ผังแสดงการพยากรณ์ด้วย ML ผ่าน FastAPI

การ Deploy AI สู่ Production ด้วย FastAPI

การโหลดโมเดล

from fastapi import FastAPI
sentiment_model = None
def load_model():
    global sentiment_model
    sentiment_model = SentimentAnalyzer("trained_model.joblib")
    print("Model loaded successfully")
load_model()
Model loaded successfully
การ Deploy AI สู่ Production ด้วย FastAPI

Lifespan event ของ FastAPI

ผังอธิบาย lifespan ของ FastAPI

การ Deploy AI สู่ Production ด้วย FastAPI

Lifespan event ของ FastAPI

from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Load the ML model
    load_model()
    yield
app = FastAPI(lifespan=lifespan)
การ Deploy AI สู่ Production ด้วย FastAPI

การตรวจสอบสถานะ (Health checks)

 

@app.get("/health")
def health_check():
    if sentiment_model is not None:
        return {"status": "healthy", 
                "model_loaded": True}
    return {"status": "unhealthy", 
            "model_loaded": False}

คำสั่ง Curl:

curl -X GET \
  "http://localhost:8080/health" \
  -H "accept: application/json"

ผลลัพธ์:

{
  "status": "healthy",
  "model_loaded": true
}
การ Deploy AI สู่ Production ด้วย FastAPI

มาฝึกกันเถอะ!

การ Deploy AI สู่ Production ด้วย FastAPI

Preparing Video For Download...