Sub topic 2
What Changes When the Model Is a Dependency: The Anatomy of an LLM App
This chapter assumes you know the classic ML lifecycle (train, validate, deploy, monitor), can write Python, and have called a model through an HTTP or SDK API. It builds a map of the parts of an LLM application. Later chapters return to each part in depth.
From owning a model to depending on one
In classic MLOps you own the model. You collect data, train, validate, package the weights, and serve them. Most of your operational effort goes into the data and training pipeline, and the model is the product of that pipeline.
In an LLM application you usually do none of that. A provider or an open-weights project trained the model. You call it through an API, or you host weights you did not train. The model becomes a dependency, like a database or a payment service. Your application is everything around that dependency, and that wrapper decides how well the product behaves.
This changes what you ship, what can break, and who controls the change schedule.
| Concern | Classic MLOps | LLM application |
|---|---|---|
| Main artifact | Trained weights | Prompt, model ID, settings, retrieval config |
| Source of behavior | Your training data | Pretrained model plus your instructions and context |
| Typical change | Retrain on new data | Edit a prompt, swap a model, change retrieval |
| Output | Label, score, or number | Free-form text or structured text |
| Correctness check | Metric against labels | Checks, rubrics, human or model grading |
| Upstream changes | Rare, under your control | Provider deprecations and silent updates |
| Cost driver | Training compute, serving instances | Tokens per request |
Some things carry over unchanged: version control, CI, staged rollouts, monitoring, and incident response. What changes is which artifacts you version and what "correct" means.
The components of an LLM app
A typical request passes through these components.
- Input handling. Validate the user input, strip or flag anything unsafe, and enforce length limits.
- Retrieval (optional). Fetch documents, records, or search results that the model needs but does not know.
- Prompt assembly. Combine instructions, retrieved context, conversation history, and the user input into the text sent to the model.
- Model call. Send the prompt with a model identifier and sampling settings. Receive text and token counts.
- Output handling. Parse, validate, and filter the response, then retry or fall back if it fails.
- Observability. Record what happened at each step.
Each box is a place where behavior can change and where a bug can hide. In a classic service, a bad prediction usually points at the model or its features. Here a bad answer might come from a retrieval miss, a truncated prompt, a changed model version, or an output parser that dropped a field. You cannot tell which without a record of each step. That is why observability is a component rather than an add-on.
What you version
Pinning a Git commit of your code is not enough to reproduce behavior. The same code can produce different results if any of these changed:
- The prompt template. Instructions, examples, and formatting rules.
- The model identifier. A name such as a dated snapshot, or an alias that the provider may repoint.
- Sampling settings. Temperature, top-p, maximum output tokens, stop sequences.
- Retrieval configuration. The index contents, chunk size, embedding model, and number of documents returned.
- Output schema and parsing rules. What the application expects back.
- Guardrail rules. Filters and policies applied before and after the call.
The next chapter treats prompts and settings as versioned artifacts in detail. For now, the point is that these pieces form one unit of behavior. Changing any single one is a release.
The following program shows the shape of that unit. It runs a small pipeline with a stand-in model function, so you can execute it without an API key. The fake_model function replaces your real client.
import json
from dataclasses import dataclass, asdict
@dataclass(frozen=True)
class AppConfig:
prompt_template: str
model: str
temperature: float
max_output_tokens: int
retriever_top_k: int
index_version: str
DOCS = [
"Refunds are issued within 5 business days of approval.",
"Duplicate charges are reversed automatically after review.",
"Passwords can be reset from the account settings page.",
]
def retrieve(query: str, k: int) -> list[str]:
"""Rank documents by how many query words they share."""
words = set(query.lower().split())
scored = sorted(
DOCS,
key=lambda d: len(words & set(d.lower().split())),
reverse=True,
)
return scored[:k]
def fake_model(model: str, prompt: str, temperature: float, max_tokens: int) -> dict:
"""Stand-in for a real API client. Returns text and token counts."""
return {
"text": "Duplicate charges are reversed after review.",
"input_tokens": len(prompt.split()),
"output_tokens": 7,
}
def answer(config: AppConfig, question: str) -> dict:
if not question.strip() or len(question) > 2000:
raise ValueError("question must be 1 to 2000 characters")
context = retrieve(question, config.retriever_top_k)
prompt = config.prompt_template.format(
context="\n".join(context), question=question
)
result = fake_model(
config.model, prompt, config.temperature, config.max_output_tokens
)
text = result["text"].strip()
if not text:
raise RuntimeError("empty model output")
return {"answer": text, "context": context, "usage": result}
config = AppConfig(
prompt_template="Use only this context:\n{context}\n\nQuestion: {question}",
model="example-model-2026-01",
temperature=0.2,
max_output_tokens=200,
retriever_top_k=2,
index_version="docs-2026-11-01",
)
print(json.dumps(asdict(config), indent=2))
print(json.dumps(answer(config, "Why was I charged twice?"), indent=2))Notice that AppConfig holds the model ID, the sampling settings, and the retrieval settings next to the prompt. Logging asdict(config) with each request lets you answer "what exactly produced this output?" later.
What breaks differently
Treating the model as a dependency creates failure modes that classic serving rarely has.
Silent upstream change
A provider may update a model behind an alias, or retire a snapshot on a published date. Your code and tests are unchanged, but outputs shift. Pin to dated identifiers where the provider offers them, and track deprecation notices as you would for any external API.
Failures that look like successes
A model call that returns HTTP 200 can still contain a wrong, empty, truncated, or badly formatted answer. A truncated response (the model hit the output token limit) is a common case. Status codes tell you the transport worked. They say nothing about quality, so your application needs checks on the content itself.
Context limits and truncation
Each model accepts a bounded number of tokens, covering prompt plus output. If retrieval returns too much or conversation history grows, something gets cut. If the cut happens silently, the model answers without the facts it needed, and the output still reads fluently.
Rate limits and partial availability
Provider APIs enforce request and token limits. Under load you will see throttling errors that a self-hosted model on your own instances would not produce in the same way. Plan for retries with backoff, timeouts, and a fallback path.
Quality that depends on wording
A small edit to a prompt can change results across many inputs, in either direction. Classic code has the same risk, but unit tests catch it. Here, correctness is statistical, so you need an evaluation set to see the effect.
Where classic MLOps still applies
Do not discard your existing practice.
- Data pipelines. Retrieval indexes, evaluation sets, and feedback logs are datasets. They need versioning, lineage, and quality checks.
- CI/CD. Tests still run on every change. The tests change shape, as the evaluation chapter explains.
- Monitoring. Latency, error rate, and traffic still matter, with token usage and quality signals added.
- Drift. The data changes (user questions, documents) even if you never retrain anything. You still watch for it.
- Reproducibility and audit. You still need to say which configuration produced a given output.
A map for the rest of the tutorial
Each component above leads to a later topic.
- Prompt assembly and the model call lead to versioned artifacts.
- The model call leads to non-deterministic outputs and how to evaluate them.
- Retrieval leads to context pipelines and their failure modes.
- The trace store leads to tracing, monitoring, and cost and latency work.
- Input and output checks lead to guardrails and prompt injection.
A first step you can take today, before any of those chapters: put every setting that affects behavior into one structured object, and log it, or a hash of it, with each request. That one habit makes every later practice easier.
Exercise
A team's support bot starts giving worse answers on Monday. Nobody deployed code, and the prompt file in Git is unchanged. List three components of the LLM app that could still have changed, and name one record that would help you tell them apart.
Show answer
Possible causes include: (1) the provider updated the model behind an alias such as "latest"; (2) the retrieval index was rebuilt or its documents changed, so the context differs; (3) a setting such as temperature or maximum output tokens changed through an environment variable, or a longer conversation history now truncates the prompt. A per-request trace that logs the model identifier, the index version, the sampling settings, and the token counts would show which one differs between last week's requests and this week's.
Exercise
An API call returns HTTP 200 with a one-sentence answer that stops mid-word. Which part of the app should have caught this, and what field from the model response would you check?
Show answer
The output handling step (output checks) should catch it. Check the finish reason (often called stop reason) to see whether generation ended because of the output token limit, and compare output tokens to the configured maximum. If the response was truncated, retry with a higher limit or return a controlled error instead of passing the partial text to the user.