載入預訓練模型

使用 FastAPI 將 AI 佈署到生產環境

Matt Eckerle

Software and Data Engineering Leader

目前架構

顯示以 FastAPI 進行 ML 預測的流程圖

使用 FastAPI 將 AI 佈署到生產環境

載入模型的挑戰

解說請求/回應生命週期的圖示

等待 API 回應而沮喪的男子

使用 FastAPI 將 AI 佈署到生產環境

在請求前載入模型

顯示以 FastAPI 進行 ML 預測的流程圖

使用 FastAPI 將 AI 佈署到生產環境

載入模型

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
使用 FastAPI 將 AI 佈署到生產環境

FastAPI lifespan 事件

解說 FastAPI lifespan 的流程圖

使用 FastAPI 將 AI 佈署到生產環境

FastAPI lifespan 事件

from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Load the ML model
    load_model()
    yield
app = FastAPI(lifespan=lifespan)
使用 FastAPI 將 AI 佈署到生產環境

健康檢查

 

@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
}
使用 FastAPI 將 AI 佈署到生產環境

一起來練習吧!

使用 FastAPI 將 AI 佈署到生產環境

Preparing Video For Download...