Artificial Intelligence — Level 4: MLOps, Generative AI & Responsible AI
Free preview

Serving models with an API

1 / 3

Patterns

  • Online (real-time) API
  • Batch predictions
  • On-device / edge
2 / 3

FastAPI

  • Pydantic input validation
  • Load model once
  • /predict and /health
3 / 3

Concerns

  • Latency and throughput
  • Versioning
  • Logging inputs and outputs

Lecture notes

Serving patterns

  • Online inference — a request returns a prediction in milliseconds (fraud check during payment, recommendation on a page).
  • Batch inference — predictions computed periodically for many records (nightly dropout-risk scores) and stored in a database. Simpler and cheaper when real time is not needed.
  • Edge inference — on phones or devices (offline crop diagnosis).
  • Streaming — predictions on event streams (Kafka) for near-real-time use cases.

A prediction API with FastAPI

from fastapi import FastAPI
from pydantic import BaseModel, Field
import joblib, pandas as pd

app = FastAPI(title='Dropout risk API', version='1.2.0')
model = joblib.load('models/dropout_v1_2.joblib')     # load once at start-up

class Student(BaseModel):
    attendance: float = Field(ge=0, le=1)
    assignments_submitted: int = Field(ge=0)
    avg_quiz: float = Field(ge=0, le=20)
    city: str

@app.get('/health')
def health():
    return {'status': 'ok', 'model_version': '1.2.0'}

@app.post('/predict')
def predict(s: Student):
    X = pd.DataFrame([s.model_dump()])
    proba = float(model.predict_proba(X)[0, 1])
    return {'risk': proba, 'flag': proba >= 0.35, 'model_version': '1.2.0'}

Run with uvicorn main:app --host 0.0.0.0 --port 8000; interactive docs appear at /docs.

Production concerns

  • Validate inputs (types, ranges) — Pydantic rejects bad requests with clear errors.
  • Latency (time per request) and throughput (requests per second); batch requests and use multiple workers.
  • Return and log the model version with each prediction for traceability.
  • Log inputs, outputs and latency (respecting privacy) — needed for monitoring and debugging.
  • Authentication and rate limiting for the API.
  • Specialised servers: TorchServe, TensorFlow Serving, NVIDIA Triton, BentoML, or managed platforms (Vertex AI, SageMaker, Azure ML).
Want to go further?
22 h · Enroll to access every lesson and earn the certificate.
Get Started Free