返回结构化预测响应

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

Matt Eckerle

Software and Data Engineering Leader

部署模型的挑战

展示使用 FastAPI 进行机器学习预测的流程图

 

 

  1. 正确接收输入数据
  2. 验证输入并处理错误
  3. 进行预测
  4. 返回结构化响应
使用 FastAPI 在生产环境中部署 AI

定义请求结构

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

text: str
sentiment: str
confidence: float
使用 FastAPI 在生产环境中部署 AI

创建预测端点

@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"] )

输入 JSON:

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

 

响应:

{
    "text": "This movie was fantastic!",
    "sentiment": "POSITIVE",
    "confidence": 0.95
}
使用 FastAPI 在生产环境中部署 AI

错误处理

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"
    )

模型预测失败时的响应

{
    "detail": "Prediction failed",
    "status_code": 500
}
使用 FastAPI 在生产环境中部署 AI

测试端点

# 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
}
使用 FastAPI 在生产环境中部署 AI

Vamos praticar!

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

Preparing Video For Download...