การส่งคืนการตอบสนองแบบมีโครงสร้าง

การ Deploy AI สู่ Production ด้วย FastAPI

Matt Eckerle

Software and Data Engineering Leader

ความท้าทายในการ deploy โมเดล

ผังแสดงการพยากรณ์ด้วย ML และ FastAPI

 

 

  1. รับข้อมูลนำเข้าอย่างถูกต้อง
  2. ตรวจสอบข้อมูลและจัดการข้อผิดพลาด
  3. ทำการพยากรณ์
  4. ส่งคืนการตอบสนองที่มีโครงสร้างชัดเจน
การ Deploy AI สู่ Production ด้วย FastAPI

การกำหนดโครงสร้าง request

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

text: str
sentiment: str
confidence: float
การ Deploy AI สู่ Production ด้วย FastAPI

การสร้าง endpoint สำหรับพยากรณ์

@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
}
การ Deploy AI สู่ Production ด้วย FastAPI

การจัดการข้อผิดพลาด

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
}
การ Deploy AI สู่ Production ด้วย FastAPI

การทดสอบ 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
}
การ Deploy AI สู่ Production ด้วย FastAPI

มาฝึกกันเถอะ!

การ Deploy AI สู่ Production ด้วย FastAPI

Preparing Video For Download...