加载预训练模型

使用 FastAPI 在生产环境中部署 AI

Matt Eckerle

Software and Data Engineering Leader

当前结构

展示使用 FastAPI 进行机器学习预测的流程图

使用 FastAPI 在生产环境中部署 AI

加载模型的挑战

请求/响应生命周期示意图

一个男子在等待 API 响应,表情焦急

使用 FastAPI 在生产环境中部署 AI

在请求前加载模型

展示使用 FastAPI 进行机器学习预测的流程图

使用 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 生命周期事件

说明 FastAPI 生命周期的流程图

使用 FastAPI 在生产环境中部署 AI

FastAPI 生命周期事件

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...