Xử lý các kiểu đầu vào khác nhau trong FastAPI

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Nhà hàng vs API

Một nhà hàng được ví với đầu vào của API

Triển khai AI vào môi trường sản xuất với FastAPI

Luồng xác thực

 

 

  • Dữ liệu đi vào qua request
  • Xác thực đầu vào bằng Pydantic
  • Xử lý các kiểu dữ liệu theo yêu cầu của model
  • Gửi đầu vào đã xử lý cho model

Lưu đồ giải thích việc xác thực request

Triển khai AI vào môi trường sản xuất với FastAPI

Hệ thống kiểm duyệt bình luận

 

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

class CommentText(BaseModel): content: str

Hình biểu tượng hộp bình luận

Triển khai AI vào môi trường sản xuất với FastAPI

Endpoint cho số thực dấu phẩy động

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()}
Triển khai AI vào môi trường sản xuất với FastAPI

Endpoint cho đầu vào văn bản

@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) }

Đầu ra cho bình luận: Sign up for free

{
    "issues": ["free", "sign up"],
    "needs_moderation": 2
}
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...