Tại sao cần triển khai mô hình?
Mô hình AI chỉ có giá trị khi người dùng cuối sử dụng được. FastAPI là framework lý tưởng để xây dựng AI API nhờ hiệu năng cao và type safety.
Xây dựng Prediction API
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import joblib
import numpy as np
app = FastAPI(title="AI Prediction API")
# Load mô hình đã train
model = joblib.load("model.pkl")
scaler = joblib.load("scaler.pkl")
class PredictRequest(BaseModel):
features: list[float]
class PredictResponse(BaseModel):
prediction: int
probability: float
label: str
@app.post("/predict", response_model=PredictResponse)
async def predict(request: PredictRequest):
try:
X = np.array(request.features).reshape(1, -1)
X_scaled = scaler.transform(X)
pred = model.predict(X_scaled)[0]
proba = model.predict_proba(X_scaled)[0].max()
labels = {0: "Negative", 1: "Positive"}
return PredictResponse(
prediction=int(pred),
probability=float(proba),
label=labels[int(pred)]
)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.get("/health")
async def health():
return {"status": "healthy", "model": "loaded"}
Dockerize
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Monitoring
import time
from fastapi import Request
@app.middleware("http")
async def log_requests(request: Request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
print(f"{request.method} {request.url.path} - {duration:.3f}s")
return response
Workflow hoàn chỉnh: Train → Save model → FastAPI → Docker → Deploy. Đây chính là MLOps cơ bản.