在 FastAPI 中處理不同輸入型別

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

Matt Eckerle

Software and Data Engineering Leader

餐廳 vs API

把餐廳比作 API 的輸入

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

驗證流程

 

 

  • 請求帶入資料
  • 使用 Pydantic 驗證輸入
  • 依模型需求處理各種資料型別
  • 將處理後的輸入送入模型

請求驗證流程圖

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

留言審核系統

 

class CommentMetrics(BaseModel):
    length: int           
    user_karma: int     
    report_count: int

class CommentText(BaseModel): content: str

留言方塊圖示

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

浮點數輸入的端點

app = FastAPI()

@app.post("/predict")
def predict_score(data: CommentMetrics):
features = np.array([ data.length, data.user_karma, data.report_count ])
model = CommentScorer() prediction = model.predict(features)
return {"prediction": round(prediction, 2), "input": data.dict()}
使用 FastAPI 將 AI 佈署到生產環境

文字輸入的端點

@app.post("/analyze_text")

def analyze(comment: CommentText):
forbidden = ["spam", "hate", "free" "fake", "sign up"]
text_lower = comment.lower()
issues = [word for word in forbidden if word in text_lower]
return { "issues": issues, "needs_moderation": len(issues) }

留言「Sign up for free」的輸出

{
    "issues": ["free", "sign up"],
    "needs_moderation": 2
}
使用 FastAPI 將 AI 佈署到生產環境

一起來練習吧!

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

Preparing Video For Download...