MODULE 2.8

🛠️ MLOps and Production

What happens after the prototype works: versioning code, prompts, and models; evaluating with every change; deploying without surprises; measuring latency, quality, and cost; and responding when something breaks. It’s the difference between a demo and a service people trust.

7
Topics
~60
Minutes
Technical
Level
Practical
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🧭 From notebook to service

MLOps is the practice of putting machine learning systems into production and keeping them running. It combines what software development already knows (version control, testing, automated deployment, monitoring) with challenges specific to AI: behavior depends on data and models that change, and the output is nondeterministic.

With LLMs, many people talk about LLMOps. The center of gravity shifts: instead of training models, you usually choose a ready-made model, write prompts, and set up document retrieval and tools. But the discipline is the same—and so is the most common mistake: treating a prototype that “worked on my machine” as if it were a product.

📘 New terms

Production is the environment where real users depend on the system. Inference is using the model to generate a response (the opposite of training). Nondeterministic means the same input can produce different outputs—which is why AI tests measure success rates instead of comparing a single result.

What it is

A continuous cycle: version what defines behavior, evaluate before release, deploy gradually, observe in production, respond to incidents, and turn each lesson into a new version.

1 · Data and prompts everything versioned 2 · Offline evaluation test set 3 · Gradual deployment canary + rollback 4 · Monitoring latency, cost, quality 5 · Incidents runbook and postmortem 6 · New version lessons become tests the cycle doesn’t end at deployment each cycle adds a new test to the set
How to read: the top line (blue) happens before users see the change; the bottom line (cyan), after. The arrow on the left is what real projects most often miss: what went wrong in production needs to come back as a test case, or the same error will return in the next version.

✓ Signs it’s ready

  • ✓Someone other than the author can bring up the service by following a README.
  • ✓There is a test set and a baseline score.
  • ✓Every request has a log with the version, latency, and result.
  • ✓Rolling back to the previous version takes minutes, not hours.

✗ Signs it’s a prototype

  • ✗The prompt lives in a notebook cell and changes without being recorded.
  • ✗“Testing” means running three examples and deciding it looks good.
  • ✗No one knows how much the system costs per month.
  • ✗The problem only shows up when a customer complains.

Why learn

Building a prototype with an LLM is easy; keeping a reliable service running is still hard. If you master the full cycle, you can put AI to real use, defend the project with numbers, and sleep soundly after deployment.

Key concepts

MLOps / LLMOps
AI treated as software
Production
users depend on it
Inference
model use
Continuous cycle
errors become tests
2

🗂️ Version everything

In ordinary software, the code defines behavior. In an AI system, behavior depends on five things at the same time: the code, the prompt, the model, the data (for training, evaluation, and the knowledge base being queried), and the configuration (temperature, token limits, enabled tools). If any of these change without being recorded, you can’t explain why today’s response differs from yesterday’s.

The rule of thumb: a prompt is code. Keep it in a file in the repository, review it, and give it a version. Pin the model by its exact name and version, never by a nickname like “latest” or “the newest”—providers and Ollama itself update nicknames, and behavior changes without you touching anything.

📘 New terms

Model registry (model registry) is a catalog of model versions with metrics and status (testing, production, retired)—MLflow has one. DVC is a tool that versions large data files alongside git. Release is the uniquely named package that brings together the versions of everything going into production.

What it is

Give each production version an identifier that points to the code commit, prompt version, exact model, evaluation data version, and configuration used—so any response can be reproduced.

release 1.4.2 one name for everything code commit a3f9c1e (git) prompt prompts/triage.v7.md model exact name + version evaluation · cases v3 configuration temperature, limits
How to read: the release in the center is what you record in every log and every incident. From it, anyone can find the exact five pieces that produced a response. If one of the ends is “loose” (has no version), the release can’t be reproduced. The identifiers are examples.
WhatWhere to version itCommon mistake
Codegit, with a tag for each releaseDeploying something that hasn’t been committed
PromptFile in the repository, reviewed in a PREditing the prompt directly in the provider’s dashboard
ModelName and version fixed in the configuration; model registryUse an alias that the provider updates
DataDVC, a versioned bucket, or a dated tableTest set edited without history
ConfigurationVersioned config file or environment variablesDifferent temperature in each environment

💡 Tip

In Ollama, ollama show <model> shows the details of the installed model and ollama list shows each model’s identifier. Record that identifier with the release: if someone runs it ollama pull again and the model changes, you’ll notice.

Why learn

Without complete versioning, you can't investigate an incident, compare two versions, or fulfill an audit request (“Which system made this decision in March?”). It's cheap to do at the start and very expensive to reconstruct later.

Key concepts

A prompt is code
file, revision, version
Pinned model
never “latest”
Release
one name for all five pieces
Reproducible
recreate the same response
3

🧪 Continuous evaluation

In module 2.7, you built a test set and measured a classifier by hand. Here, it becomes a quality gate: an automated test that runs whenever the prompt, model, or code changes and blocks publication if the result falls below the baseline. It’s the same principle as software tests, adapted to outputs that vary.

There are three layers of evaluation. Deterministic checks: the JSON is valid, the label is on the list, and the response isn’t too long. Metrics against correct answers: accuracy, precision, recall. And, for open-ended text, LLM as a judge with a written rubric—useful, but it needs to be checked against human scores on a sample.

📘 New terms

CI (continuous integration) means running tests automatically with every commit, using services such as GitHub Actions or GitLab CI. Regression is when something that worked stops working after a change. LLM as a judge means using one model to score another model’s responses according to explicit criteria.

What it is

Run the test set automatically with every change and treat a drop in quality as a failing test: the version doesn’t go to production until someone explains or fixes it.

Try this: quality gate with pytest, using the classifier.py from module 2.7.

# Installation: pip install pytest openai   |   ollama pull qwen2.5:7b
# Structure:  classificador.py   evals/casos.jsonl   test_qualidade.py
#
# evals/casos.jsonl — one case per line (replace with 30+ real, anonymized examples):
# {"texto": "My order has been stuck for a week", "esperado": "entrega"}
# {"texto": "The payment slip expired, and I can't generate another one", "esperado": "pagamento"}

# test_qualidade.py
import json
import pathlib
from classificador import classificar, ROTULOS

CASOS = [json.loads(l) for l in
         pathlib.Path("evals/casos.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()]
LINHA_DE_BASE = 0.80   # <replace with the value measured in the current production version>

def test_formato_valido():
    for caso in CASOS[:5]:
        saida = classificar(caso["texto"])
        assert saida["rotulo"] in ROTULOS, saida

def test_acuracia_nao_cai():
    erros = []
    for caso in CASOS:
        previsto = classificar(caso["texto"])["rotulo"]
        if previsto != caso["esperado"]:
            erros.append((caso["texto"], caso["esperado"], previsto))
    acc = 1 - len(erros) / len(CASOS)
    print(f"\nacurácia={acc:.0%} (linha de base {LINHA_DE_BASE:.0%})")
    for e in erros:
        print("  ERRO:", e)
    assert acc >= LINHA_DE_BASE, f"regressão: {acc:.0%} < {LINHA_DE_BASE:.0%}"

How to check: run pytest -q -s test_qualidade.py. With the current prompt, both tests should pass and show the accuracy. Now deliberately break the prompt (change the list of labels in the instruction) and run it again: test_acuracia_nao_cai should fail with the message “regression.” That’s the gate working.

Deterministic

Format, required fields, length, prohibited words. Cheap and fast: run it every time.

With an answer key

Accuracy and per-label metrics against answers annotated by people. This is the main gate.

LLM as a judge

For open-ended responses. Written rubric and periodic checks against human scores.

Why learn

Prompts and models change all the time, and an improvement in one case often makes another worse. The automated gate turns “I think it's better” into a comparable number and keeps silent regressions from reaching users.

Key concepts

Quality gate
blocks regression
Baseline
today’s number
CI
test with every commit
LLM as a judge
score with a rubric
4

🚀 Deploy and serving

Serving means putting the model behind a stable interface—almost always an HTTP API—that other systems call. The service needs things the notebook didn’t: input validation, a time limit for each call, a fallback response when the model fails, a health endpoint, and a log for each request.

As for how it runs: real time (the response comes back right away, as in a chat) or batch (processes thousands of items overnight, at lower cost and with tolerance for delays). The model can be an external API or your own server—Ollama to get started, servers like vLLM as volume grows—packaged in a Docker container so it runs the same way on any machine.

📘 New terms

Fallback is the fallback response when the main one fails (an “other” label, a standard message, an alternate model). Canary deployment means sending a small fraction of traffic to the new version and gradually increasing it if the metrics look good. Rollback means going back to the previous version.

What it is

Wrap the model in a service with a clear contract (input, output, errors), time and size limits, a fallback response, and gradual rollout with a quick way to revert.

Goal: a classification service with a timeout, fallback, health check, and structured logging (app.py).

# Installation: pip install fastapi uvicorn openai   |   ollama pull qwen2.5:7b
import json, logging, time, uuid
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from openai import OpenAI

VERSAO = "classificador-1.4.2"          # <the release that's live>
MODELO = "qwen2.5:7b"
ROTULOS = {"entrega", "pagamento", "produto", "elogio", "outro"}
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
                timeout=20, max_retries=1)   # never wait forever
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("servico")
app = FastAPI()

class Pedido(BaseModel):
    texto: str

@app.get("/health")
def health():
    return {"ok": True, "versao": VERSAO, "modelo": MODELO}

@app.post("/classificar")
def classificar(p: Pedido):
    if not p.texto.strip() or len(p.texto) > 4000:
        raise HTTPException(422, "empty or too long text")
    rid, t0, tokens = str(uuid.uuid4()), time.perf_counter(), 0
    try:
        r = client.chat.completions.create(
            model=MODELO, temperature=0, response_format={"type": "json_object"},
            messages=[{"role": "system", "content": "Classify as: " + ", ".join(sorted(ROTULOS))
                       + '. Reply only with {"rotulo": "..."}'},
                      {"role": "user", "content": p.texto}])
        rotulo = json.loads(r.choices[0].message.content).get("rotulo")
        tokens = r.usage.total_tokens if r.usage else 0
        status = "ok" if rotulo in ROTULOS else "fora_da_lista"
    except Exception as e:                     # timeout, model offline, invalid JSON
        rotulo, status = None, f"erro:{type(e).__name__}"
    if rotulo not in ROTULOS:
        rotulo = "outro"                       # fallback: the system never returns junk
    ms = round((time.perf_counter() - t0) * 1000)
    log.info(json.dumps({"rid": rid, "versao": VERSAO, "status": status,
                         "ms": ms, "tokens": tokens, "rotulo": rotulo}))
    return {"rotulo": rotulo, "status": status, "versao": VERSAO, "request_id": rid}

How to check: run it with uvicorn app:app --port 8000 2>&1 | tee servico.log. In another terminal: curl -s localhost:8000/health should return the version; curl -s -X POST localhost:8000/classificar -H 'Content-Type: application/json' -d '{"texto":"meu pedido não chegou"}' should return "rotulo":"entrega". Stop Ollama and repeat: the response should contain "rotulo":"outro" and an error status, without taking down the service.

router divides the traffic most small fraction stable version 1.4.1 continues serving requests canary 1.4.2 closely monitored metrics within limits? yes → increase in steps up to 100% no → roll back to 1.4.1 errors, latency, fallback, evaluation canary share, step by step little one quarter half all example steps — define your own
How to read: The thickness of the arrows shows how much traffic goes to each version. The dashed box is the decision made at each step, based on the same metrics as in Topic 5. The key point: the stable version stays online the entire time, so rolling back only requires changing how the router divides traffic.

💡 Tip

Before the canary, there’s an even safer step: shadow mode. The new version receives a copy of real requests, but its response isn’t sent to the user — it goes only to the log, where you compare it with the stable version.

Why learn

Models slow down, go offline, and return unexpected formats. A service with a timeout, fallback, and gradual rollout turns these failures into controlled degradation instead of an error screen for the customer.

Key concepts

Timeout
per-call limit
Fallback
fallback response
Canary
gradual traffic rollout
Real time × batch
urgency determines the cost
5

📈 Monitoring

An AI system can be “online” and still be wrong. The server responds on time, with no HTTP error, but quality has dropped because customers started writing about a new topic or because the provider changed the model. That’s why monitoring looks at four groups of signals: technical, quality, cost, and data.

The foundation is the structured log that the service in Topic 4 already records: one JSON line per request, with version, status, latency, and tokens. From there, you can build dashboards (Grafana), alerts, and tracing across services (OpenTelemetry). For LLMs, there are purpose-built observability tools, such as the open-source Langfuse, which stores the prompt, response, and evaluation for each call.

📘 New terms

Percentile: p95 latency is the time below which 95% of requests fall — it shows the experience of the unluckiest users, which the average hides. Drift (drift) is a change over time in the kind of data that arrives or in the relationship between data and the correct response. Observability means being able to answer “why did this happen?” using the records.

What it is

Continuously track whether the service is fast, available, accurate, and within budget, with alerts that notify you before the user does — and enough records to investigate each case.

p50 half are faster p95 1 in 20 is slower p99 the tail that frustrates users fast slow (response time →) illustrative format, not to scale
How to read: Each bar shows how many requests took that long. LLM responses have a long tail (the cyan bars): long responses and GPU queues make some take much longer. Alert on p95, not the average—the average can stay steady while the tail gets worse.
CategoryWhat to measureTypical alert
Technicalp50/p95 latency, error rate, timeoutsp95 stays above the agreed threshold for 10 minutes
QualityFallback rate, evaluator score on a sample, user feedbackFallback rate doubles compared with the previous week
CostTokens per request, daily spend, and spend per customerDaily spend exceeds the budget
Data (drift)Label distribution, text length, language"Other" label grows without explanation

Try this: calculate p50, p95, errors, and label distribution from the servico.log.

# metricas.py — no external dependencies
import json, statistics, sys
from collections import Counter

linhas = []
for l in open(sys.argv[1] if len(sys.argv) > 1 else "servico.log", encoding="utf-8"):
    l = l.strip()
    if l.startswith("{"):
        try:
            linhas.append(json.loads(l))
        except json.JSONDecodeError:
            pass

if len(linhas) < 2:
    sys.exit("too few requests in the log; make a few calls first")

ms = [x["ms"] for x in linhas]
q = statistics.quantiles(ms, n=100, method="inclusive")  # q[49] = p50, q[94] = p95
status = Counter(x["status"] for x in linhas)
rotulos = Counter(x["rotulo"] for x in linhas)
nao_ok = sum(v for k, v in status.items() if k != "ok")

print(f"requests: {len(linhas)}")
print(f"latency p50={q[49]:.0f} ms  p95={q[94]:.0f} ms  max={max(ms)} ms")
print(f"non-ok: {nao_ok / len(linhas):.1%}  {dict(status)}")
print(f"tokens/req (average): {statistics.mean(x['tokens'] for x in linhas):.0f}")
print("labels:", {k: f"{v / len(linhas):.0%}" for k, v in rotulos.most_common()})

How to check: with the service from topic 4 running, make about 20 calls with varied text and run python3 metricas.py servico.log. You should see p50 lower than p95, the fraction of non-ok responses, and the label distribution. Stop Ollama, make more calls, and run it again: the fraction of non-ok responses should rise. That’s the number an alert monitors.

Why learn

AI systems degrade silently. If you measure latency, quality, cost, and drift, you can spot the problem on Monday morning by checking a dashboard—instead of hearing about it from an important customer on Friday night.

Key concepts

95th percentile
the typical worst case
Structured log
one JSON line per call
Drift
the data has changed
Alert
warns you before the customer does
6

💰 Cost and performance

With paid APIs, costs are proportional to tokens: input tokens (prompts, documents, history) and output tokens (the response), usually at different rates. With local models, the costs are hardware, energy, and maintenance. In both cases, the same levers work: send less text, generate less text, use the smallest model that gets the job done, and don’t repeat work.

Performance and cost go hand in hand: fewer tokens also mean faster responses. The order that usually gets the best results is to measure first (how much each type of request costs), cut obvious waste (resending the entire history, including documents that weren’t needed), and only then consider switching models.

📘 New terms

Prompt caching: several providers charge less when the beginning of the prompt repeats across calls—so put fixed instructions at the beginning and variable content at the end. Model routing: a small model handles simple cases, and only the difficult ones go to the large model. Quantization: store the model weights using fewer bits so they take up less memory, with some loss in quality.

What it is

Measure cost and latency by request type and apply the levers—leaner prompts, output limits, caching, batching, routing, and smaller models—then check the test set to make sure quality hasn’t dropped.

✓ Levers that work

  • ✓Set an output token limit and use a short format (JSON instead of a paragraph).
  • ✓Put fixed instructions at the beginning of the prompt to take advantage of caching.
  • ✓Batch work that doesn’t need an immediate response.
  • ✓Cache answers to identical, repeated questions.

✗ Savings that cost you

  • ✗Switch models without running the test set.
  • ✗Cut context until the model starts making things up.
  • ✗Cache responses that depend on the user or the moment.
  • ✗Remove timeouts and retries to “gain speed.”

Goal: estimate the monthly cost of a paid API workflow from measured token usage.

# custo.py — fill in with YOUR numbers (prices change; check the provider’s page)
PRECO_ENTRADA_POR_MILHAO = 0.0   # <US$ per 1 million input tokens>
PRECO_SAIDA_POR_MILHAO = 0.0     # <US$ per 1 million output tokens>
COTACAO_DOLAR = 0.0              # <R$ per US$ on the day>

FLUXOS = {  # name: (requests per day, input tokens, output tokens) — measured averages
    "triagem":  (2000, 350, 20),
    "resumo":   (150, 6000, 400),
    "<outro>": (0, 0, 0),
}

total = 0.0
for nome, (req, t_in, t_out) in FLUXOS.items():
    dia = req * (t_in * PRECO_ENTRADA_POR_MILHAO + t_out * PRECO_SAIDA_POR_MILHAO) / 1_000_000
    mes = dia * 30 * COTACAO_DOLAR
    total += mes
    print(f"{nome:10s} R$ {mes:10.2f}/month   ({req} req/day, {t_in}+{t_out} tokens)")
print(f"{'TOTAL':10s} R$ {total:10.2f}/month")
# Simulate: what happens if the summary cuts input in half? And with half the requests?

How to check: use the average token counts from metricas.py (Topic 5) and the provider’s current prices. Run python3 custo.py and check one workflow by hand with the calculator. Start optimizing the workflow with the highest monthly cost—often it isn’t the one with the most requests.

Why learn

AI projects are canceled because of unpredictable costs more often than because of poor quality. Knowing how to estimate, measure, and reduce spending without losing accuracy is what lets you take a pilot to the whole company.

Key concepts

Input × output
different prices
Prompt caching
fixed at the beginning
Routing
small first
Quantization
less memory, some loss
7

🚨 Incidents and rollback

An incident in an AI system doesn’t always mean “it’s down.” The assistant might respond in an inappropriate tone, a classifier might send everything to “other,” an agent might take an action it shouldn’t, or costs might triple overnight. The response follows the same order: contain the damage first, then understand the cause.

Containment usually means one of three actions: return to the previous release (rollback), turn off the feature with a configuration flag, or activate degraded mode (fallback to a simple rule or human support). All of this needs to be ready and tested before an incident—in a runbook, not in someone’s head.

📘 New terms

Runbook is the written set of steps for handling each type of problem, with commands ready to run. Feature flag is a configuration switch that turns a feature on or off without a new deploy. Blameless postmortem is an incident review focused on causes and safeguards, not blame—so people can share what really happened.

What it is

A process agreed on in advance for detecting, containing, communicating, fixing, and learning from failures, always ending with a new safeguard—usually one more case in the test suite or one more alert.

1 · Detect. A monitoring alert or user report. Record the time and the release currently running.

2 · Contain. Rollback, feature flag, or degraded mode. Investigate afterward.

3 · Communicate. Who is affected, what has been done, and when the next update will be.

4 · Fix. Reproduce it using the release and request log; fix it; pass the quality gate.

5 · Learn. Blameless postmortem and one new safeguard: a test case, alert, or limit.

Goal: a minimal runbook (RUNBOOK.md) to keep in the service repository.

# RUNBOOK — <service name>
On-call owner: <name / channel>     Dashboard: <dashboard link>
Current release: <e.g., classifier-1.4.2>  Previous stable release: <1.4.1>

## Symptom A — fallback or error rate rises
1. Check /health and whether the model responds (ollama ps / provider status).
2. If it started after a deploy: ROLLBACK -> <exact command or step>.
3. If the model is down: activate degraded mode -> <flag/variable and value>.

## Symptom B — inappropriate responses (tone, content, wrong action)
1. Turn off the feature: <feature flag> = off.
2. Save 5 examples (request_id) to reproduce the issue, without personal data.
3. Notify <responsible team> and the data protection officer if personal data is involved.

## Symptom C — daily cost exceeds <limit>
1. Check tokens by workflow (metricas.py) and which workflow changed.
2. Lower the request limit: <config>.  3. Investigate loops or abuse.

## After every incident
- [ ] Blameless postmortem within <N> business days (timeline, cause, safeguards)
- [ ] New case in evals/casos.jsonl reproducing the problem
- [ ] New alert or limit if the problem was discovered late

How to check: Run a drill. Ask someone on the team who didn’t write the service to handle Symptom A using only the runbook, with Ollama deliberately stopped. If they need to ask anything, add the answer to the runbook.

💡 Tip

Keep a one-line record for each failure: date, what broke, the smallest possible fix, and whether the cause was a prompt or infrastructure issue. After a few entries, the pattern emerges, and you stop rebuilding what only needed a safeguard.

Why learn

Every system in production will fail at some point. The difference between a five-minute incident and a five-hour one is having the recovery path ready and rehearsed—and the difference between a team that repeats mistakes and one that improves is a postmortem that leads to a safeguard.

Key concepts

Contain first
investigate afterward
Runbook
steps with commands
Feature flag
turns off without a deploy
Postmortem
blameless, with safeguards

✅ Module summary

✓
Version all five pieces — code, prompt, model, data, and configuration under one release.
✓
The test suite is the gate — no version passes if it falls below the baseline.
✓
Serve with limits and roll out gradually — timeout, fallback, canary, and rollback.
✓
Measure, spend thoughtfully, and learn from failures — p95, cost per workflow, runbook, and postmortem.

Next module:

2.9 — AI Ethics and Governance ⚖️