Yapılandırılmış tahmin yanıtı döndürme

FastAPI ile Üretime AI Dağıtımı

Matt Eckerle

Software and Data Engineering Leader

Modelleri dağıtırken zorluklar

FastAPI ile ML tahmini akış şeması

 

 

  1. Girdiyi düzgün al
  2. Gelen veriyi doğrula ve hataları yönet
  3. Tahmin yap
  4. İyi yapılandırılmış yanıt döndür
FastAPI ile Üretime AI Dağıtımı

İstek yapısını tanımlama

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

text: str
sentiment: str
confidence: float
FastAPI ile Üretime AI Dağıtımı

Tahmin endpoint'i oluşturma

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

Girdi JSON'u:

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

 

Yanıt:

{
    "text": "This movie was fantastic!",
    "sentiment": "POSITIVE",
    "confidence": 0.95
}
FastAPI ile Üretime AI Dağıtımı

Hata yönetimi

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

Model tahmin yapamazsa yanıt

{
    "detail": "Prediction failed",
    "status_code": 500
}
FastAPI ile Üretime AI Dağıtımı

Endpoint'i test etme

# Örnek istek
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 ile Üretime AI Dağıtımı

Hadi pratik yapalım!

FastAPI ile Üretime AI Dağıtımı

Preparing Video For Download...