在伺服器啟動時載入 AI 模型
你需要部署一個已訓練的情緒分析模型,用來協助審核使用者的留言。為了確保零停機,API 必須在啟動後立刻可以分析使用者留言。
在這個練習中,你將實作 FastAPI 的 lifespan 事件,有效率地載入模型,來建立留言審核系統。SentimentAnalyzer 模型類別已為你定義並匯入。
本練習屬於課程
使用 FastAPI 將 AI 佈署到生產環境
練習說明
- 從
contextlib模組匯入情境管理器裝飾器,以建立 lifespan 事件。 - 使用 FastAPI 的情境管理器裝飾器來定義
lifespan事件函式,確保在啟動時載入模型。 - 在
lifespan事件中呼叫載入模型的函式,讓模型在啟動時載入。 - 呼叫
yield,讓伺服器的載入流程得以繼續。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the context manager decorator from contextlib module
from contextlib import ____
sentiment_model = None
def load_model():
global sentiment_model
sentiment_model = SentmentAnalyzer("sentiment_model.joblib")
# Use FastAPI's context manager to define lifespan event
@____
def lifespan(app: FastAPI):
# Call the function to load the model
____
____