Sirva el modelo de Production
Cargue el modelo promovido en su servicio de FastAPI.
Sirva el modelo de Production es una lección gratuita de MLOps Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MLOps Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MLOps Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
From Registry to API
The promoted model is sitting in the registry. Now you load it into a FastAPI service so real requests can get predictions. 🌐
Reference It by Alias
Build a model URI that points at the champion alias. Your code never hardcodes a version, so promotions just work.
MODEL_URI = "models:/churn-classifier@champion"Load the Model
Use mlflow.pyfunc.load_model to pull the production model down into memory as a callable Python object.
import mlflow.pyfunc
model = mlflow.pyfunc.load_model(MODEL_URI)Load Once at Startup
Loading is slow, so do it once when the app boots, not per request. Use a FastAPI lifespan handler to load before traffic arrives.
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app):
app.state.model = mlflow.pyfunc.load_model(MODEL_URI)
yieldCreate the App
Wire the lifespan into your FastAPI instance. From here on, the loaded model lives on app.state and is shared by every request.
from fastapi import FastAPI
app = FastAPI(lifespan=lifespan)Validate the Input
Define a Pydantic model for the request body so malformed input is rejected before it ever reaches the model.
from pydantic import BaseModel
class Features(BaseModel):
tenure: int
monthly_charges: floatWrite the Predict Endpoint
Turn the validated input into a row and call the model. The predict method returns the prediction you send back as JSON.
@app.post("/predict")
def predict(f: Features):
pred = app.state.model.predict([[f.tenure, f.monthly_charges]])
return {"prediction": int(pred[0])}Add a Health Check
A tiny /health route lets orchestrators know the service is up and the model finished loading before they route traffic.
@app.get("/health")
def health():
return {"status": "ok"}Run the Server
Launch with uvicorn and your model is live on HTTP. Any client that can POST JSON can now get predictions.
uvicorn serve:app --host 0.0.0.0 --port 8000Quick Check
Why load the model in a lifespan handler instead of inside the predict function?
Updating the Live Model
To ship a new model, re-point the champion alias and restart the service. It loads the new version at startup automatically.
Same Model Everywhere
Because the service pulls from the registry, dev, staging, and prod can all load the exact same artifact by alias. No copy-paste of weights.
Recap: Serving the Production Model
You loaded the champion at startup, validated input, exposed /predict and /health, and ran it with uvicorn. Your model is now a live service. ✅
Preguntas frecuentes
¿La lección «Sirva el modelo de Production» es gratis?
Sí — el texto completo de «Sirva el modelo de Production» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MLOps Academy, actualiza a CoddyKit PRO. El curso de MLOps Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Sirva el modelo de Production»?
Cargue el modelo promovido en su servicio de FastAPI. Practicas MLOps Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar MLOps Academy?
No se requiere experiencia previa. MLOps Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Sirva el modelo de Production»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de MLOps Academy?
Sí. Cada lección de MLOps Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Entrene y registre el modelo
- Promueva el mejor modelo a Production
- Sirva el modelo de Production
- Trace el recorrido completo de una predicción