Tải mô hình đã huấn luyện

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Cấu trúc hiện tại

Lưu đồ dự đoán ML với FastAPI

Triển khai AI vào môi trường sản xuất với FastAPI

Thách thức khi tải mô hình

Sơ đồ vòng đời request/response

Người đàn ông bực bội chờ phản hồi API

Triển khai AI vào môi trường sản xuất với FastAPI

Tải mô hình trước khi nhận request

Lưu đồ dự đoán ML với FastAPI

Triển khai AI vào môi trường sản xuất với FastAPI

Tải mô hình

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
Triển khai AI vào môi trường sản xuất với FastAPI

Sự kiện lifespan của FastAPI

Sơ đồ luồng sự kiện lifespan của FastAPI

Triển khai AI vào môi trường sản xuất với FastAPI

Sự kiện lifespan của FastAPI

from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Load the ML model
    load_model()
    yield
app = FastAPI(lifespan=lifespan)
Triển khai AI vào môi trường sản xuất với FastAPI

Kiểm tra tình trạng (Health check)

 

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

Lệnh curl:

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

Đầu ra:

{
  "status": "healthy",
  "model_loaded": true
}
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...