在 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

Vamos praticar!

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

Preparing Video For Download...