Trả về phản hồi dự đoán có cấu trúc

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

Matt Eckerle

Software and Data Engineering Leader

Thách thức khi triển khai mô hình

Lưu đồ minh họa dự đoán ML với FastAPI

 

 

  1. Nhận dữ liệu đầu vào đúng cách
  2. Xác thực dữ liệu đến và xử lý lỗi
  3. Tạo dự đoán
  4. Trả về phản hồi có cấu trúc rõ ràng
Triển khai AI vào môi trường sản xuất với FastAPI

Định nghĩa cấu trúc request

from pydantic import BaseModel
class PredictionRequest(BaseModel):
    text: str
class PredictionResponse(BaseModel):

text: str
sentiment: str
confidence: float
Triển khai AI vào môi trường sản xuất với FastAPI

Tạo endpoint dự đoán

@app.post("/predict")
def predict_sentiment(request: PredictionRequest):
    if sentiment_model is None:
        raise HTTPException(
            status_code=503,
            detail="Model not loaded"
        )

result = sentiment_model(request.text)
return PredictionResponse( text=request.text, sentiment=result[0]["label"], confidence=result[0]["score"] )

Input JSON:

{"text": "This movie was fantastic!"}

 

Phản hồi:

{
    "text": "This movie was fantastic!",
    "sentiment": "POSITIVE",
    "confidence": 0.95
}
Triển khai AI vào môi trường sản xuất với FastAPI

Xử lý lỗi

try:
  result = sentiment_model(request.text)
  return PredictionResponse(
        text=request.text,
        sentiment=result[0]["label"],
        confidence=result[0]["score"]
    )
except Exception:
  raise HTTPException(
        status_code=500,
        detail="Prediction failed"
    )

Phản hồi khi mô hình không dự đoán được

{
    "detail": "Prediction failed",
    "status_code": 500
}
Triển khai AI vào môi trường sản xuất với FastAPI

Kiểm thử endpoint

# Example request
import requests

response = requests.post(
    "http://localhost:8000/predict",
    json={"text": "Great product!"}
)
print(response.json())
{
    "text": "Great product!",
    "sentiment": "POSITIVE",
    "confidence": 0.998
}
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...