Prompt and model observability
Operate a versioned LLM service
LLMOps is the practice of keeping a language-model application observable, evaluable and recoverable as its dependencies change. A support FAQ answer depends on more than model weights: prompt template, output contract, retrieval index, embedding revision, tool policy, application code and runtime settings all matter. Give the entire combination an immutable release ID, such as r2. Store the template and approved configuration in a registry; a mutable alias such as stable points to a release but is not the release identity. The mock registry below records three of these dependencies. In practice include the rest and record requested versus returned model identifiers when available. A provider can change behavior even with the same alias; versioning supports diagnosis, not bitwise reproducibility. The example records token counts, elapsed milliseconds and retrieval count while deliberately dropping raw prompt and answer.
def trace_metadata(event, registry): # Trusted registry and server-generated IDs; no request text is copied. version = event["version"] if version not in registry: raise ValueError("unknown release") fields = ("input_tokens", "output_tokens", "latency_ms", "retrieved_count") if any(type(event.get(k)) is not int or event[k] < 0 for k in fields): raise ValueError("invalid measurement") if event.get("outcome") not in ("ok", "timeout", "rate_limit", "invalid"): raise ValueError("unknown outcome") return {"version": version, **registry[version], **{k: event[k] for k in fields}, "outcome": event["outcome"]}
registry = {"r2": {"model": "mock-m@1", "prompt": "faq@2", "index": "docs@3"}}event = dict(version="r2", input_tokens=120, output_tokens=30, latency_ms=410, retrieved_count=2, outcome="ok", raw_prompt="invented private text", raw_output="invented answer")print(trace_metadata(event, registry))Design traces, metrics and logs
A trace follows one task through related spans: retrieval, inference attempt, validation and final response. Generate opaque correlation IDs on the server and propagate them between spans; use parent/child links rather than copying the request body. A metric aggregates many observations (error count, latency histogram, token count), whereas a log describes an individual event. Track request outcome separately from the outcome of each attempt. A timeout may have consumed tokens; a successful response can still contain an incorrect answer. Track retrieval latency, count, index version and authorization decision separately from generation. Do not use raw queries, user IDs or unique trace IDs as metric labels: cardinality and exposure rise. The example uses fixed trusted IDs and a closed outcome vocabulary; registry contents must themselves be validated. In production allowlist fields and values before exporting, restrict log access and retention, and avoid raw prompts, document excerpts, headers, secrets and error bodies. Hashing a short private string does not guarantee anonymity. OpenTelemetry GenAI conventions offer a shared vocabulary, but the local dictionary is not an implementation of that evolving standard.
Account for every attempt
Separate input and output tokens and multiply by their respective rates per million. The example charges two hypothetical dollars per million input tokens and six per million output tokens. Attempt one reports 120 input tokens and zero output; attempt two reports 120 and 30. Total estimated cost = (240×2 + 30×6)/1,000,000 = 0.00066 USD. Fraction is Python’s exact rational type, avoiding intermediate rounding; convert to a display decimal only at the reporting boundary. The empty list returns zero only for a confirmed absence of attempts. If usage is missing, report unknown rather than zero; reconcile with provider invoices and mark estimates, units, effective rate dates and currencies. Cached input, reasoning tokens, audio, storage and other charges may have separate accounting rules; do not add subsets twice. Aggregate cost per completed task using all attempt costs (including failed tasks) divided by successful task count, and show the denominator. If none complete, the ratio is undefined.
from fractions import Fraction
def token_cost(attempts, input_rate, output_rate): # Hypothetical USD per million tokens; integer rates for this lab. if any(type(x) is not int or x < 0 for x in (input_rate, output_rate)): raise ValueError("invalid rates") if any(type(i) is not int or type(o) is not int or min(i, o) < 0 for i, o in attempts): raise ValueError("invalid counts") return sum((Fraction(i * input_rate + o * output_rate, 1000000) for i, o in attempts), Fraction(0))
# Both attempts report known usage, even though the first failed.print(token_cost([(120, 0), (120, 30)], 2, 6))print(token_cost([], 2, 6))Instrument responsibly
Measure request rate, errors, first-token latency, full response latency, output tokens per second and evaluation results by release and relevant slices. A percentile such as p95 needs a sample size and window; averaging p95 values from instances is not the global p95. Sampling traces helps cost but can hide rare failures; keep aggregate counts and explicitly record sampling policies. Track missing telemetry and delayed events. For an incident compare like traffic, model and prompt versions, index revisions and measurement windows. Observability indicates symptoms, not causation or correctness; use a held-out evaluation suite and human review from Chapter 47. MLflow Prompt Registry and tracing can link prompts to traces; no integration is executed here.
Practice and common mistakes
Change the mock event outcome to timeout; the trace still retains measured token counts. Add a new raw field and confirm it is excluded. Try an unknown release or a negative latency; both must be rejected. Compute the cost of a retry with different known counts and explain why actual billing may differ. Do not record an entire event by default, claim a token estimate is an invoice, silently treat unknown usage as free, or assume a lower latency means higher quality. Check your trace policy with a reviewer before exporting real telemetry.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prompt and model observability quiz
Assess trace minimization, cost, fallback and release recovery.
Why record the resolved release rather than only the stable alias?
What should the trace export by default?
What is the known estimated cost of 240 input and 30 output tokens at 2 and 6 USD per million?
How should a missing usage report be represented?
What does a lower p95 latency establish?