Sub topic 11
Tracing outputs back to prompt versions
This chapter assumes you can render a template, load a versioned prompt file, and pin an application to a version, as covered in earlier chapters. It also assumes you can read JSON and use Python's logging module.
Versioning gives every prompt change a name. Tracing connects that name to what happened in production. Without tracing, a user reports a bad answer and you can't tell which prompt, which model settings, or which inputs produced it. With tracing, you can answer that question in minutes.
Why a version number alone is not enough
A pinned version tells you what the application is supposed to use. It does not tell you what a particular call used. The two can differ for several reasons:
- A deployment is half rolled out, so some servers run the old pin and some run the new one.
- A rollback happened at 14:00, and you need to know which outputs came before it.
- A developer edited a template file locally without bumping the version.
- An alias such as
stablepointed at one version this morning and another this afternoon.
The fix is to record facts at the moment of the call, not to infer them later from configuration. Each model call should write one log record that states exactly what was used.
What to record
A useful record contains everything that could change the output, plus enough identifiers to find the call again.
| Field | Why it matters |
|---|---|
| `call_id` | A unique ID so a user report or support ticket can point at one call |
| `prompt` and `prompt_version` | The template name and the concrete version, never an alias |
| `template_hash` | A short digest of the template text, which catches edits that did not change the version |
| `model` | The model name or identifier, since a model change alters output as much as a prompt change |
| `temperature` and other sampling settings | Different settings produce different outputs from the same prompt |
| `latency_ms` | Lets you see whether a new version is slower or produces longer outputs |
| `output_chars` | A cheap proxy for output length, available without storing the output |
| `timestamp` | Ordering and correlation with deployments |
Notice what is not in the table: the rendered prompt and the raw output. Those are often needed, but they carry privacy and storage costs. A later section covers that decision.
A minimal log function
The simplest version records the prompt name, version, model, temperature, and output size as one JSON object per log line.
import json, logging
logger = logging.getLogger("llm")
def log_call(prompt_name, prompt_version, model, temperature, output):
logger.info(json.dumps({
"prompt": prompt_name,
"prompt_version": prompt_version,
"model": model,
"temperature": temperature,
"output_chars": len(output),
}))One JSON object per line is called JSON Lines. It is easy to write, easy to append to, and easy to parse with standard tools. Avoid free-text messages such as "Called summarize v1.2.0". They are readable but hard to filter and count.
Putting tracing in one place
If every call site writes its own log line, some will forget, and the field names will drift. Put the load, render, call, and log steps in a single wrapper so no call can skip tracing.
The wrapper below assumes the file layout from the storage chapter, prompts/<name>/<version>.yaml, and the summarize template at version 1.2.0. The generate argument is any function that takes a rendered prompt and returns text, so you can pass a real client or a stub.
import hashlib
import json
import logging
import time
import uuid
from pathlib import Path
from string import Template
import yaml
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("llm")
PINNED = {"summarize": "1.2.0"}
def load_prompt(name, version):
path = Path("prompts") / name / f"{version}.yaml"
return yaml.safe_load(path.read_text())
def template_hash(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
def traced_call(generate, name, values, model, temperature):
version = PINNED[name]
prompt = load_prompt(name, version)
rendered = Template(prompt["template"]).substitute(values)
call_id = str(uuid.uuid4())
started = time.perf_counter()
output = generate(rendered, model=model, temperature=temperature)
latency_ms = round((time.perf_counter() - started) * 1000)
logger.info(json.dumps({
"call_id": call_id,
"prompt": name,
"prompt_version": version,
"template_hash": template_hash(prompt["template"]),
"model": model,
"temperature": temperature,
"latency_ms": latency_ms,
"output_chars": len(output),
}))
return output, call_id
def fake_generate(rendered, model, temperature):
return "Prompt templates keep instructions apart from input."
output, call_id = traced_call(
fake_generate,
"summarize",
{"style": "concise", "text": "Prompt templates separate fixed instructions from variable input."},
model="example-model",
temperature=0.2,
)
print(call_id, output)Three details are worth noting.
- The wrapper reads the version from
PINNED, then logs that same value. It never logs the pin lookup separately, so the record cannot disagree with what was loaded. - The wrapper returns
call_idto the caller. Show it in an error report, a feedback button, or an API response header, so a user can quote it when something goes wrong. template_hashis computed from the template text, not the rendered prompt. It identifies the template file contents, not the user's input.
Log the resolved version, not the alias
If your system lets callers say stable or latest, resolve the alias to a concrete version before logging. A record that says prompt_version: "stable" is useless a week later, because stable has moved. A record that says 1.2.0 stays correct forever.
The same rule applies to models. If your provider offers a floating name like example-model-latest, log the specific model identifier the API reports in its response when one is available. Otherwise you cannot tell whether a change in behavior came from your prompt or from the provider.
Tracing a bad output
Here is how the records get used. A user reports a poor summary and sends the call ID.
The steps are:
- Search the logs for the call ID.
- Read
prompt_version,template_hash,model, andtemperaturefrom the record. - Open the matching version file in Git and read its change note.
- Compare the logged
template_hashwith the hash of the file at that version. If they differ, someone edited the file without bumping the version, and that is a process failure to fix separately. - Reproduce the call with the same template and settings. Add the failing input to your regression cases so the problem cannot return unnoticed.
Reproduction needs the original input. That leads to the main design decision in tracing.
Deciding what to store: hashes, previews, or full text
Logging the full rendered prompt and the full output makes debugging easy. It also copies user data, possibly personal or confidential, into a log system that usually has weaker access control and longer retention than your database.
You have three options.
- Metadata only. Log the fields in the table above. This is safe and cheap, but you cannot see what the model said.
- Metadata plus hashes or sizes. Add a hash of the input and output. You can confirm that two calls had identical input without storing it. You still cannot read the content.
- Full content in a separate, restricted store. Keep the metadata log open to engineers. Write the rendered prompt and the output to a store with tighter access, a short retention period, and the same
call_idas the key.
Most teams choose the third option for debugging and the first for dashboards. Whatever you choose, apply the escaping and validation rules from earlier chapters to what you log. An input that tries to inject instructions into a prompt can also inject fake log lines if you write free text. Writing JSON through json.dumps escapes newlines and quotes, which is another reason to avoid plain string formatting in logs.
Using the logs to compare versions
Logs also answer questions about versions in aggregate. During a rollout you might ask how many calls used each version, or whether the new version produces longer outputs. Because the records are JSON Lines, a short script is enough.
import json
from collections import Counter, defaultdict
counts = Counter()
chars = defaultdict(list)
with open("llm.log", encoding="utf-8") as f:
for line in f:
record = json.loads(line)
key = (record["prompt"], record["prompt_version"])
counts[key] += 1
chars[key].append(record["output_chars"])
for key, n in sorted(counts.items()):
average = sum(chars[key]) / n
print(key, n, round(average))This script expects a file that contains only the JSON records. Send the llm logger to its own file handler, or filter the file first, so other log lines do not break json.loads.
A jump in average output length after a release is a signal to investigate, but it does not prove the new version is worse. Treat these numbers as a prompt to look at examples, not as a quality score. Quality still comes from the regression tests and from human review.
Edge cases and failure modes
- Chains of prompts. If one request calls three templates, give each call its own record and add a shared
request_id. Otherwise you cannot tell which step produced the bad text. - Retries and fallbacks. If a failed call is retried on a different model, log each attempt. A single record that shows only the final model hides the first failure.
- Missing records. If the model call succeeds but the log write fails, you have an untraceable output. Wrap logging so it never raises into the request path, and monitor for gaps, for example by comparing call counts with the provider's usage report.
- Clock and ordering. Log timestamps in UTC. Deployment times and rollbacks only line up with calls if they use the same clock.
- Version drift. A
template_hashthat does not match the Git file for the logged version shows that the deployed file differs from the reviewed one. Alert on this. - Sampling. If you log only a fraction of calls to save cost, a rare failure may have no record. Always log metadata for every call, and sample only the expensive full-content store.
Summary
Tracing closes the loop that versioning opens. Log one structured record per call, resolve aliases to concrete versions, add a template hash to detect silent edits, and decide deliberately how much content to store. Then any output can be traced to the prompt text, change note, model, and settings that produced it.
Exercise
A record in your logs shows prompt_version: "stable". Why is this a problem, and what should the code log instead?
Show answer
The alias stable can point to different versions over time, so the record no longer says which template produced the output. The code should resolve the alias to a concrete version such as 1.2.0 before the call and log that value.
Exercise
You find that the template_hash in a log record does not match the hash of prompts/summarize/1.2.0.yaml in Git. Name one likely cause and one action to take.
Show answer
A likely cause is that the deployed template file was edited without bumping the version, or a different file was deployed than the one reviewed. Action: redeploy from the reviewed commit, and add a check in the release process that fails when the hash of a deployed file differs from the hash in Git.
Exercise
Your team wants to debug bad outputs but handles customer data. Describe a logging setup that supports both goals.
Show answer
Write metadata (call ID, prompt name and version, template hash, model, temperature, latency, output length) to the normal log for every call. Write the rendered prompt and output to a separate store with restricted access and short retention, keyed by the same call ID. Redact sensitive variables before storing.