1.6 The MVP Is Ready, What Did We Forget?
Figure 8. What a production-ready application needs.
When a prototype starts turning into a real application, a whole universe of new, unforeseen problems opens up. If earlier you tested individual prompts, now you have to take care of the system as a whole. And it turns out the situation is more complicated than it seemed. The model you used in the demo may be updated by the provider. Some prompts may start behaving differently. Without a quality evaluation system, degradation can go unnoticed until users start complaining.
An LLM application requires the same engineering approach as any other software: testing, monitoring, versioning, and documentation (Fig. 8). The specifics are that the model's behavior is nondeterministic and depends on external factors the developer does not control. The provider may change the model, the API speed, or the pricing. Accordingly, testing and monitoring approaches must take this into account.
Quality Metrics at Different Levels
The choice of metrics depends on the specific task. For classification, standard metrics apply: accuracy, precision, recall, and F1-score. For text generation, evaluation is harder: you need to measure the relevance of the answer, the completeness of the information, the correctness of facts, and conformance to style and format.
It is useful to split metrics into groups. Technical metrics measure how the system works: latency, tokens per request, API error rate, cost per request, and availability. Output quality metrics assess the results: classification accuracy, conformance to the expected format, completeness of the extracted information, and answer relevance. Finally, business metrics link the system's work to the product's goals: user satisfaction, conversion, the time it takes to handle a request, and the cost of customer service.
Each level of metrics matters and helps answer different questions. Technical metrics answer "does the system work?". Quality metrics answer "does it work correctly?". Business metrics answer "does it bring value?".
Here is a simple class for collecting and analyzing metrics:
class MetricsCollector:
def __init__(self):
self.metrics = defaultdict(list)
def record_request(self, request_id, metrics_dict):
timestamp = datetime.utcnow().isoformat()
for metric_name, value in metrics_dict.items():
self.metrics[metric_name].append({
"request_id": request_id,
"timestamp": timestamp,
"value": value
})
def get_summary(self, metric_name, period_hours=24):
cutoff = datetime.utcnow() - timedelta(hours=period_hours)
recent = [
m["value"] for m in self.metrics[metric_name]
if datetime.fromisoformat(m["timestamp"]) > cutoff
]
if not recent:
return None
return {
"count": len(recent),
"mean": sum(recent) / len(recent),
"min": min(recent),
"max": max(recent),
"p50": sorted(recent)[len(recent) // 2],
"p95": sorted(recent)[int(len(recent) * 0.95)]
}
The get_summary method returns statistics for a metric over the last 24 hours: the number of observations, the mean, the minimum, the maximum, the median, and the 95th percentile. Such statistics help spot problems: if the average response time has suddenly jumped, that is a sign that something is wrong.
Building a Test Set
A test set for an LLM application includes example inputs with expected results or evaluation criteria. And here an interesting problem appears: for generative tasks, the "expected result" is often not unique. An answer to a question can be phrased in many ways and still be correct. This makes testing much harder.
Several types of test cases are used. Exact matches apply to classification and extraction of structured data: we know the expected category is COMPLAINT, or the JSON must contain certain fields. Checking for key elements works for text generation: the answer must contain certain facts or mentions, or must not contain forbidden elements. Negative tests verify that the system correctly handles invalid input or refuses forbidden actions.
Here is a structure for representing test cases:
class TestCase:
def __init__(self, input_data, expected=None, validators=None, tags=None):
self.input_data = input_data
self.expected = expected
self.validators = validators or []
self.tags = tags or []
def evaluate(self, actual_output):
results = {"passed": True, "checks": []}
if self.expected:
exact_match = actual_output == self.expected
results["checks"].append({
"type": "exact_match",
"passed": exact_match
})
if not exact_match:
results["passed"] = False
for validator in self.validators:
check_result = validator(actual_output, self.input_data)
results["checks"].append(check_result)
if not check_result["passed"]:
results["passed"] = False
return results
def contains_keywords(keywords):
def validator(output, input_data):
output_lower = output.lower()
missing = [kw for kw in keywords if kw.lower() not in output_lower]
return {
"type": "contains_keywords",
"passed": len(missing) == 0,
"missing": missing
}
return validator
def valid_json_schema(schema):
def validator(output, input_data):
try:
json_match = re.search(r'\{.*\}', output, re.DOTALL)
if not json_match:
return {"type": "json_schema", "passed": False, "error": "No JSON found"}
data = json.loads(json_match.group())
validate(data, schema)
return {"type": "json_schema", "passed": True}
except Exception as e:
return {"type": "json_schema", "passed": False, "error": str(e)}
return validator
Validators are functions that take the model's output and the input data and return the result of the check. You can create simple validators (keyword checks) and complex ones (JSON schema validation). The main point is that each test clearly defines what it checks and why.
Logging
The must-have in production is logging. Usually it makes sense to log: the input data (with sensitive information masked), the prompts after formatting, the raw model response, the parsed result, metadata (time, model, parameters), and errors if they occurred.
Here is an implementation of a logger with personal-data masking:
class LLMLogger:
def __init__(self, storage_backend):
self.storage = storage_backend
def log_request(self, request_id, data):
log_entry = {
"request_id": request_id,
"timestamp": datetime.utcnow().isoformat(),
"input": self.mask_pii(data.get("input")),
"prompt": data.get("prompt"),
"model": data.get("model"),
"parameters": data.get("parameters"),
"raw_response": data.get("raw_response"),
"parsed_response": data.get("parsed_response"),
"latency_ms": data.get("latency_ms"),
"tokens": data.get("tokens"),
"error": data.get("error")
}
self.storage.write(log_entry)
def mask_pii(self, text):
if not text:
return text
masked = re.sub(r'\b\d{10,11}\b', '[PHONE]', text)
masked = re.sub(r'\b[\w.-]+@[\w.-]+\.\w+\b', '[EMAIL]', masked)
return masked
Note that masking personal data is not just good practice; it is often a legal requirement. Phone numbers and email addresses are replaced with placeholders, but the overall structure of the logs remains clear for analysis.
Structured logging makes it possible to build dashboards and perform in-depth analysis. You can find correlations between certain patterns of input data and errors. You can trace how a single change to the prompt affected quality. Without detailed logging, such analysis is simply impossible.
Monitoring Costs
The cost of an LLM application is made up of input and output tokens. Each provider has its own prices, but the general principle is the same: input tokens are cheaper, output tokens are more expensive. If you generate long responses, costs grow quickly. If the average cost per request has suddenly risen, it may mean the model has started generating longer answers, which can be a sign that quality has dropped. Or that traffic has increased. In any case, such changes must be surrounded by as many flags and warnings as possible.
class CostTracker:
PRICING = {
"gpt-5": {"input": 0.03, "output": 0.06},
"gpt-5-mini": {"input": 0.01, "output": 0.03},
"gpt-5-nano": {"input": 0.0005, "output": 0.0015}
}
def __init__(self):
self.daily_costs = defaultdict(float)
self.request_costs = []
def record(self, model, input_tokens, output_tokens):
pricing = self.PRICING.get(model, {"input": 0.01, "output": 0.03})
cost = (input_tokens * pricing["input"] + output_tokens * pricing["output"]) / 1000
today = datetime.utcnow().date().isoformat()
self.daily_costs[today] += cost
self.request_costs.append({
"timestamp": datetime.utcnow().isoformat(),
"model": model,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cost": cost
})
return cost
def get_daily_summary(self, date=None):
date = date or datetime.utcnow().date().isoformat()
day_requests = [r for r in self.request_costs if r["timestamp"].startswith(date)]
if not day_requests:
return None
return {
"date": date,
"total_cost": sum(r["cost"] for r in day_requests),
"request_count": len(day_requests),
"avg_cost_per_request": sum(r["cost"] for r in day_requests) / len(day_requests),
"total_input_tokens": sum(r["input_tokens"] for r in day_requests),
"total_output_tokens": sum(r["output_tokens"] for r in day_requests)
}
Based on such data, it makes sense to set up alerts: if the daily cost exceeds the set budget, if the average cost per request has risen sharply, or if the number of requests has jumped.
Fighting Latency
The latency of LLM calls is significantly higher than that of typical microservices and even other machine learning services. If a classic machine learning prediction takes tens of milliseconds, a call to a language model can take several seconds. P50 is often 1–3 seconds, and P95 can be 5–10 seconds. This strongly affects the architecture of the application and the user experience.
I will limit myself to three pieces of advice. The first: streaming the response. When possible, the model generates the answer in parts (chunks), and you start sending them to the user immediately. The user sees the text as it appears instead of waiting for the full response. Psychologically, this is experienced as a faster answer.
async def stream_response(client, messages):
async with client.responses.stream(
model="gpt-5-mini",
input=messages,
) as stream:
full_response = ""
async for event in stream:
if event.type == "response.output_text.delta":
full_response += event.delta
yield event.delta
The second: asynchronous processing. If a request can be handled in the background (for example, sending an email notification with the result instead of returning it synchronously), use message queues and background workers. The user gets a confirmation right away, and the result arrives later.
And the third: caching. Identical requests with temperature=0 (deterministic answers) can safely be cached. For requests with non-zero temperature, you need to answer honestly: do I want to return a once-generated answer for a repeated request? In some cases yes (an FAQ bot), in others no (creative writing).
Questions for Reflection and Practice
Theoretical questions
-
Explain the three-level system of metrics for LLM applications (technical, output quality, and business metrics) and their relationship.
-
Why is building a reliable test set for generative models harder than for classification models?
-
Which types of validators can be used for automatic evaluation of answer quality, and what are their limitations?
-
Describe the approach to regression testing of LLM applications and how it differs from testing deterministic systems.
-
What information must be logged for each request, and how do you balance the completeness of the logs with data privacy?
-
How do you organize cost monitoring and detect anomalies in API spending?
-
Which techniques help reduce the perceived latency of LLM applications for the user?
-
How do you version prompts and track the impact of changes on quality metrics?
-
Which caching strategies apply to LLM requests, and what limitations do they have?
-
How do you detect and respond to quality degradation caused by model updates from the provider?
Practical exercises
-
Implement the class
MetricsCollectorfor collecting and aggregating metrics of an LLM application, with percentile calculation. -
Create a set of 10 test cases with different validator types: exact match, presence of keywords, conformance to a JSON schema.
-
Implement
RegressionTestRunnerwith test history tracking and alerts when quality drops below a set threshold. -
Build a logging system with masking of personal data (phone numbers, emails) and structured storage.
-
Implement
CostTrackerwith daily aggregation and a function that forecasts monthly spending based on the current expenses. -
Create a latency monitoring dashboard with percentile visualization (p50, p95, p99) and alerts for anomalies.
-
Implement a prompt versioning system with change tracking and quality comparison between versions on a test set.
What's Next
In the next chapter we take a step forward and stop treating the model as a black box. We move toward building systems centered on data. The discussion covers approaches such as RAG (retrieval-augmented generation), embeddings, and vector search: techniques that let an LLM work with information that is absent from its weights but available in external sources such as databases, documents, or a codebase.