03.12 Minimal Tracing: See What Your First LLM App Did
You have made your first model calls and maybe a first tool call. They work, and you cannot see what they did. How long did each step take? How many tokens did the model use? What did it cost? Which tool did it call, and with what arguments? This lesson builds the smallest useful answer: a 60-line span recorder in plain Python that writes one JSON line per step, so you can read the story of one request from top to bottom. It is deliberately tiny. When you outgrow it, the open standard (OpenTelemetry) is the next step: 11A.1 covers it for production, and Module 11A has a lesson on the OpenTelemetry GenAI conventions.
What you'll learn
- What a trace and a span are, in plain words, and why one request becomes a small tree of spans
- How to build a span recorder with only
contextlib,time,uuidandjson, and use it around one model call and one tool call - What to record on each span: inputs (safely), outputs, latency, token counts, cost, status
- How correlation ids tie your logs to one request and to the provider's own record of the call
- What you must never log: secrets, personal data, raw prompts by default, and exception messages
- How to read a trace file with a ten-line viewer
- Where to go next, and why a recorder like this is a starting point and not a monitoring system
What you don't need
- API keys. The model in this lesson is a scripted fake, so every code block runs offline with real output. The two provider snippets (OpenAI and Anthropic) need a key and are labelled illustrative.
- Docker, a database, or any observability product. The "backend" is a text file.
- Any OpenTelemetry knowledge. This lesson is the gentle start; the standard comes later in Module 11A.
Setup
Python 3.11 or newer and the standard library. That is all. As of 1 December 2026 nothing here needs an install; if you want to try the provider snippets later, the packages are openai and anthropic (package names only; you get the newest release). Save each code block under the file name in its first comment, all in one folder, and run it with python3.
What you must be able to do after this lesson#
- Explain what a trace and a span are
- Build a span recorder in plain Python
- Add correlation ids to calls
- Read a trace to find a slow or failing step
- List what must never be logged
Why this matters for an AI engineer#
A normal program fails loudly: an exception, a 500, a stack trace. An LLM app fails quietly. It returns "success" with a wrong answer, or it succeeds after four retries and ten times the tokens you expected. The only way to find out is to have kept a record of what happened. Tracing is that record.
| You'll hear... | You'll understand it after... |
|---|---|
| "Can you pull up the trace for that request?" | Part 1 and Part 4 |
| "Why did that answer cost so much?" | 2.3 Tokens and cost on the span |
| "Give me the request id and I'll find it." | Part 3: Correlation ids |
| "We can't log that, it's customer data." | Part 5: What never to log |
| "Are we using OpenTelemetry?" | Part 6: What this recorder is not |
Part 1: What a trace is#
1.1 One request, many steps#
Think of a delivery tracking page. One parcel has one tracking number, and under it a list of scans: "left the warehouse", "arrived at the depot", "out for delivery". Each scan has a time. A trace is the tracking number: everything that happened for one request. A span is one scan: one named step with a start time, an end time, and some facts about it.
A request to a small LLM app might produce this:
request (the whole request)
llm.call #1 (the model decides to call a tool)
tool.call get_order (our code runs the tool)
llm.call #2 (the model writes the final answer)The indentation is the parent and child relationship. The tool call and both model calls happened inside the request, so they are its children.
1.2 What a span holds#
Every span in this lesson has the same fields:
| Field | Meaning |
|---|---|
trace_id |
The tracking number, shared by every span in one request |
span_id |
This step's own id |
parent_id |
The span_id of the step that contains this one (null for the first span) |
name |
What the step is: llm.call, tool.call, request |
attributes |
Facts about the step: model name, token counts, cost, tool name |
status |
ok or error |
duration_ms |
How long it took |
start_unix |
When it started, so spans can be ordered |
You will meet the same ideas, with standard names, in the OpenTelemetry GenAI conventions (11A.1, sections 3.7 to 3.13). Learning them in a tiny form first makes the standard easy to read.
Part 2: A span recorder in plain Python#
2.1 The recorder#
The trick is a context manager: a with block that does something when it starts and again when it ends. We time the block, catch an error if one happens, and write one line when the block exits. To remember "which span am I inside?" we use contextvars, Python's way of keeping a value that is private to the current task, so two requests handled at the same time do not mix up their parents.
# tracer.py (standard library only)
"""A 70-line span recorder. One JSON line per finished span."""
import contextlib
import contextvars
import json
import re
import time
import uuid
_trace_id = contextvars.ContextVar("trace_id", default=None)
_span_id = contextvars.ContextVar("span_id", default=None)
# Where finished spans go. Swap this for a file, a queue or an exporter later.
OUTPUT_PATH = "trace.jsonl"
# --- never log these -----------------------------------------------------
SECRET_RE = re.compile(r"(sk-[A-Za-z0-9_\-]{8,}|Bearer\s+[A-Za-z0-9._\-]{8,})")
EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def scrub(value):
"""Mask secrets and e-mail addresses in any string; recurse into dicts and lists."""
if isinstance(value, str):
value = SECRET_RE.sub("[SECRET]", value)
return EMAIL_RE.sub("[EMAIL]", value)
if isinstance(value, dict):
return {k: scrub(v) for k, v in value.items()}
if isinstance(value, list):
return [scrub(v) for v in value]
return value
@contextlib.contextmanager
def span(name, **attrs):
"""Time a block. Nested `with span(...)` blocks become parent and child."""
trace_id = _trace_id.get() or uuid.uuid4().hex # new trace if none is active
parent_id = _span_id.get()
span_id = uuid.uuid4().hex[:16]
t_token = _trace_id.set(trace_id)
s_token = _span_id.set(span_id)
record = {"trace_id": trace_id, "span_id": span_id, "parent_id": parent_id,
"name": name, "attributes": scrub(attrs), "status": "ok"}
start = time.perf_counter()
record["start_unix"] = round(time.time(), 3)
try:
yield record["attributes"] # the block can add attributes: attrs["tokens"] = 12
except Exception as exc:
record["status"] = "error"
record["error_type"] = type(exc).__name__ # the class name only, not the message
raise
finally:
record["duration_ms"] = round((time.perf_counter() - start) * 1000, 1)
record["attributes"] = scrub(record["attributes"])
_span_id.reset(s_token)
_trace_id.reset(t_token)
with open(OUTPUT_PATH, "a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")Four things to notice, because each is a design decision:
- The block can add attributes after it starts.
yield record["attributes"]hands the block a dict. The model call does not know its token counts until it returns, so it writes them afterwards. finallyalways writes the line, even if the block raised. A failed step is the one you most want in the file.- Only the exception's class name is stored, not its message. Messages often quote the input (Part 5 shows why).
scrubruns on everything before it is written. It is a safety net, not a plan (Part 5).
2.2 Wrapping one model call and one tool call#
Now an app to trace. The "model" is a fake that takes 50 ms and returns canned token counts, so you can run everything offline. The prices are made-up demo numbers; real prices change, so a real app reads them from your provider's pricing page or a price table you maintain (03.7 shows how).
# app.py (standard library only; the "model" is a fake so no key is needed)
import json
import time
import tracer
# Made-up demo prices in USD per million tokens. Real prices change: check your provider's pricing page.
PRICE_PER_MTOK = {"demo-model": {"input": 1.00, "output": 4.00}}
def cost_usd(model, input_tokens, output_tokens):
p = PRICE_PER_MTOK[model]
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def fake_model(messages, model="demo-model"):
"""Stands in for client.responses.create(...) or client.messages.create(...)."""
time.sleep(0.05)
if messages[-1]["role"] == "user":
return {"tool_call": {"name": "get_order", "arguments": {"order_id": "A17"}},
"usage": {"input_tokens": 120, "output_tokens": 18}}
return {"text": "Order A17 shipped on 2 December.",
"usage": {"input_tokens": 190, "output_tokens": 11}}
def get_order(order_id):
time.sleep(0.02)
return {"order_id": order_id, "status": "shipped", "ship_date": "2 December"}
def call_llm(messages, request_id):
with tracer.span("llm.call", request_id=request_id, model="demo-model") as attrs:
reply = fake_model(messages)
u = reply["usage"]
attrs["input_tokens"] = u["input_tokens"]
attrs["output_tokens"] = u["output_tokens"]
attrs["cost_usd"] = round(cost_usd("demo-model", u["input_tokens"], u["output_tokens"]), 8)
attrs["finish"] = "tool_call" if "tool_call" in reply else "stop"
return reply
def run(question, request_id):
with tracer.span("request", request_id=request_id, user_text=question):
messages = [{"role": "user", "content": question}]
reply = call_llm(messages, request_id)
call = reply["tool_call"]
with tracer.span("tool.call", request_id=request_id, tool=call["name"],
arguments=call["arguments"]) as attrs:
result = get_order(**call["arguments"])
attrs["result_chars"] = len(json.dumps(result)) # size, not content
messages += [{"role": "assistant", "content": call},
{"role": "tool", "content": result}]
final = call_llm(messages, request_id)
return final["text"]
if __name__ == "__main__":
print(run("Where is order A17? My email is ana@example.com", request_id="req-001"))Run it. The first line is the app's answer. Then we read the trace file back with a viewer:
# show_trace.py (standard library only)
import json
import sys
from collections import defaultdict
spans = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]
children = defaultdict(list)
for s in spans:
children[s["parent_id"]].append(s)
def show(parent_id, depth=0):
for s in sorted(children[parent_id], key=lambda s: s["start_unix"]):
a = s["attributes"]
extra = ""
if "input_tokens" in a:
extra = f" in={a['input_tokens']} out={a['output_tokens']} cost=${a['cost_usd']:.6f}"
print(f"{' ' * depth}{s['name']:<10} {s['duration_ms']:>7.1f} ms {s['status']}{extra}")
show(s["span_id"], depth + 1)
print("trace", spans[0]["trace_id"])
show(None)Output from running python3 app.py and then python3 show_trace.py trace.jsonl (your trace id and times will differ):
Order A17 shipped on 2 December.trace 0f95b565fb5b45969307bf7728a1c6fb
request 135.4 ms ok
llm.call 55.0 ms ok in=120 out=18 cost=$0.000192
tool.call 25.0 ms ok
llm.call 54.9 ms ok in=190 out=11 cost=$0.000234Read it like a story. The request took about 135 ms. Two model calls took about 55 ms each and the tool 25 ms, and the three together are almost all of the request. The first call used 120 input and 18 output tokens and cost a fraction of a cent. If someone says "that request felt slow", you now know where the time went.
This is one raw line of the file, so you can see exactly what was stored:
{"trace_id": "0f95b565fb5b45969307bf7728a1c6fb", "span_id": "033eacdf9c5b49f8", "parent_id": "db1680e13def4f9f", "name": "llm.call", "attributes": {"request_id": "req-001", "model": "demo-model", "input_tokens": 120, "output_tokens": 18, "cost_usd": 0.000192, "finish": "tool_call"}, "status": "ok", "start_unix": 1796180316.176, "duration_ms": 55.0}2.3 Tokens and cost on the span#
Cost is not a nice-to-have in LLM apps, because every call is metered. Four rules keep the numbers honest:
- Record what the provider reports, not your own estimate. Every provider returns a
usageobject with the real counts (03.7 has the field table). - Compute cost from tokens with a price table you control, as
cost_usd()does above. Store the tokens as well as the cost, so you can recompute when prices change. - Reuse 03.7's record shape. 03.7, 5.1 defines the per-request cost record (
provider,model,uncached_input_tokens,output_tokens,cost_usd,latency_ms,status,trace_id). Where the facts match, use the same names. This lesson shortens two to keep the code small (input_tokensstands foruncached_input_tokensbecause there is no caching here, andfinishforfinish_reason), and thetrace_idfield in 03.7's record is exactly where this lesson's trace id goes. So cost tracking started in 03.7 and a span is the same record with a start time, a parent and a name. Keep one set of field names. - Be careful with cached tokens. OpenAI's
input_tokensalready includes cached tokens, while Anthropic'sinput_tokensexcludes cache reads and writes, which have their own fields. The lesson on cost, 03.7, explains the convention to normalise this. For this lesson we assume no caching.
Both providers document these usage fields (checked on 2 December 2026): OpenAI's usage.input_tokens is the total input and includes cached tokens (usage.input_tokens_details.cached_tokens is the cached part), while Anthropic's usage.input_tokens counts only tokens after the last cache breakpoint, with cache_read_input_tokens and cache_creation_input_tokens reported separately. Both return output_tokens.
Here is how the two main providers fill the same span. This needs a key and a network, so the output is not shown. It is illustrative and was written against the field names in 03.7 and the official SDK docs; check them if the SDKs have changed.
# provider_spans.py (illustrative: needs OPENAI_API_KEY and ANTHROPIC_API_KEY)
import tracer
from openai import OpenAI
from anthropic import Anthropic
openai_client, anthropic_client = OpenAI(), Anthropic()
def ask_openai(question, request_id):
with tracer.span("llm.call", request_id=request_id, provider="openai", model="gpt-6-luna") as attrs:
resp = openai_client.responses.create(model="gpt-6-luna", input=question, max_output_tokens=200)
attrs["input_tokens"] = resp.usage.input_tokens # includes cached tokens
attrs["output_tokens"] = resp.usage.output_tokens
attrs["provider_request_id"] = resp._request_id # the provider's id for this call
return resp.output_text
def ask_anthropic(question, request_id):
with tracer.span("llm.call", request_id=request_id, provider="anthropic", model="claude-haiku-5-5") as attrs:
msg = anthropic_client.messages.create(
model="claude-haiku-5-5", max_tokens=200,
messages=[{"role": "user", "content": question}])
attrs["input_tokens"] = msg.usage.input_tokens # excludes cache reads and writes
attrs["output_tokens"] = msg.usage.output_tokens
attrs["provider_request_id"] = msg._request_id
attrs["finish"] = msg.stop_reason
return msg.content[0].textNotice how little changes: the span wraps the call, and the attributes come from the response. That is the whole idea of instrumenting a model call.
Part 3: Correlation ids#
A correlation id is one identifier that appears everywhere the same request leaves a footprint: in your logs, in your spans, and, where the provider allows it, on the call to the provider. With it, "find everything about request req-001" becomes a single search.
There are three ids worth knowing:
| Id | Who makes it | What it finds |
|---|---|---|
request_id (yours) |
Your edge: the web handler or job runner makes one per incoming request | Every log line and span for this request |
trace_id |
The recorder, once per trace | Every span in the trace |
provider_request_id |
The provider, returned on the response | The provider's record of that one call, which their support can look up |
Our recorder already writes request_id on every span in the examples above, and trace_id automatically. For the provider's id, the OpenAI and Anthropic SDKs expose _request_id on the response object, as in the snippet above. 03.10, 4.4 has the full table of where each provider takes and returns ids, with a web middleware that sets the id once at the edge.
Part 4: Reading the trace#
Once you have a file of spans, three questions repay the effort.
Where did the time go? Look at the children of the request and compare their durations. In our run the model calls dominate. If a tool were taking 2 seconds, you would see it at once.
What did it cost, and for what? Add up cost_usd over the spans of a trace for the cost of one request. Group by model or by feature to see which part of your app spends the money.
What went wrong? Filter for "status": "error". Our recorder stores the error class, so TimeoutError and ValueError are easy to tell apart.
A twelve-line script answers the first and third question across a whole file:
# summarize.py (standard library only)
import json
import sys
from collections import defaultdict
by_name = defaultdict(list)
errors = 0
for line in open(sys.argv[1], encoding="utf-8"):
s = json.loads(line)
by_name[s["name"]].append(s["duration_ms"])
errors += s["status"] == "error"
for name, ms in sorted(by_name.items()):
print(f"{name:<10} n={len(ms):<4} avg={sum(ms) / len(ms):7.1f} ms max={max(ms):7.1f} ms")
print("error spans:", errors)Run on the file from app.py it prints one row per span name (real output; your times will differ):
llm.call n=2 avg= 55.0 ms max= 55.0 ms
request n=1 avg= 135.4 ms max= 135.4 ms
tool.call n=1 avg= 25.0 ms max= 25.0 ms
error spans: 0On a file with many requests it prints the same one row per span name. Notice it reports an average and a maximum, which is crude. Averages hide the slow requests that users complain about. 11A.3 (latency, errors and SLOs) fixes that with percentiles.
Part 5: What never to log#
A trace is a copy of your user's data, stored somewhere else, read by more people than the database. Treat it as a leak risk from the first line you write.
| Never log | Why | Do this instead |
|---|---|---|
API keys, tokens, Authorization headers |
A leaked key is a leaked account | Do not put headers on spans; mask anything that looks like a key |
| Email addresses, phone numbers, names, card numbers | Personal data, often regulated | Mask them, or store a keyed hash if you need to count distinct users |
| Raw prompts and answers, by default | Users paste anything into a chat box, including passwords and medical details | Store lengths and token counts. Store text only behind a flag, for a short time, in a restricted place |
| Exception messages | Libraries quote the input inside errors | Store the exception class (TimeoutError) and a status |
| Whole tool results | Often exactly the private data the user asked about | Store the tool name, a hash or size of the result, and a status |
Our recorder has two defences, shown running here. A secret and an email address end up in a span by accident, and an exception message quotes a card number:
# redaction_and_errors.py (standard library only)
import json
import tracer
tracer.OUTPUT_PATH = "trace_errors.jsonl"
open(tracer.OUTPUT_PATH, "w").close()
# 1. A secret and an e-mail address end up in span attributes by accident.
with tracer.span("llm.call", user_text="Mail ana@example.com", auth="Bearer abc123def456ghi"):
pass
# 2. A failing call: status "error", only the exception CLASS is stored (messages can quote the prompt).
try:
with tracer.span("llm.call", model="demo-model"):
raise TimeoutError("read timed out while sending: 'my card is 4111 1111 1111 1111'")
except TimeoutError:
pass
for line in open(tracer.OUTPUT_PATH, encoding="utf-8"):
r = json.loads(line)
print(r["name"], r["status"], r.get("error_type"), r["attributes"])llm.call ok None {'user_text': 'Mail [EMAIL]', 'auth': '[SECRET]'}
llm.call error TimeoutError {'model': 'demo-model'}The email became [EMAIL], the bearer token became [SECRET], and the timeout stored TimeoutError and nothing from its message, so the card number never reached the file.
Also keep the trace file out of git (trace*.jsonl in .gitignore) and out of any chat or ticket you paste into.
Part 6: What this recorder is not, and where to go next#
Deep-dive
This recorder teaches the idea. It is not a monitoring system, and it is good to be exact about the gaps:
| Gap | What fills it |
|---|---|
| Names differ from every other tool | A standard: the OpenTelemetry GenAI semantic conventions (11A.1, sections 3.7 to 3.13) |
| One file, one machine | Exporting to a backend such as Langfuse or Arize Phoenix (11A.1, sections 5.5 to 5.11) |
| No agents: only one tool call | Nested agent spans (11A.1, section 3.11) |
| Averages only | Percentiles, error classes, SLOs, audit logs (11A.3) |
| Traces just sit there | Turning production traces into test cases (11A.4) |
| Writes on the request path | A fail-open exporter (11A.1, 4.2) |
If you already use LangChain or LangGraph, LangSmith gives you tracing with almost no code (11A.5, Part 2). It is one good option; 11A.1, section 5.10 compares it with open alternatives.
Part 7: Evaluate it#
A trace tells you what happened. It does not tell you whether the answer was good. Module 10A is where that judgement lives, and traces are its raw material.
- 10A.1 — Why evals matter is the starting point.
- 10A.7 — Evaluating agents shows how a recorded run (your span file) is graded after the fact.
- 10A.9 — Offline and online evaluation covers scoring sampled production traffic.
A tiny eval for this lesson. Check the recorder itself, with no model involved. Inputs: the trace from app.py and three seeded mistakes (a missing model attribute, a negative duration, a span whose parent id does not exist). Metric: the fraction of spans that pass a validator. Pass rule: the real trace scores 100% and each seeded mistake is caught. Writing that validator is exercise 5. The next lesson, 03.13, builds a tiny eval harness whose every case can emit one of these spans. The fuller version, for OpenTelemetry-shaped spans, is in 11A.1, sections 3.7 to 3.13.
Common misconceptions#
- "Logging is tracing." A log line is a single event. A trace keeps the structure: which step was inside which, and how long each took. You can build traces from logs only if every line carries ids and timings, which is what the recorder does.
- "I should log the full prompt so I can debug." It is the most useful and the most dangerous field. Default to sizes and ids, and capture text deliberately and briefly.
- "Tracing slows my app down." Writing one small line per step is cheap. What can hurt is writing slowly on the request path. That is a design question for later, not a reason to skip tracing.
- "The cost is on my provider's dashboard, so I don't need it in traces." The dashboard shows totals. Only a span can say which request and which step spent it.
- "I need a vendor tool before I can trace." A text file and sixty lines are enough to start. Tools add search, dashboards and teamwork; they do not replace the habit.
Key takeaways#
- A trace is everything that happened for one request. A span is one timed step inside it. Spans nest: a tool call inside a request is its child.
- A context manager makes spans cheap to add: it times the block, catches errors, and writes one line in
finally. - Record on every model call: model, input tokens, output tokens, finish reason, latency, cost. Record on every tool call: name, status, latency, result size.
- Correlation ids (your request id, the trace id and the provider's request id) turn "find everything about that request" into one search.
- Never log secrets, personal data, raw prompts, whole tool results or exception messages by default. Log sizes, hashes, ids and error classes.
- A scrubber is a safety net. Not recording the content is the policy.
- This recorder is a first step. OpenTelemetry (Module 11A) is the standard it grows into.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Trace | The record of everything that happened for one request, made of spans |
| Span | One named, timed step with attributes, a status and a parent |
| Attribute | A fact attached to a span, such as model name or token count |
| Parent and child span | A span that contains another is its parent; nesting shows which step ran inside which |
| Context manager | A with block that runs code at its start and end; the tool for timing a step |
contextvars |
Python's per-task variables; keep "the current span" correct under concurrency |
| Correlation id | One identifier carried through logs, spans and provider calls to join them |
| Provider request id | The id the provider returns for a call, used to find it in their systems |
| Scrubbing | Masking secrets and personal data before they are stored |
| Instrumentation | Code you add so a program records what it did |
Exercises#
- Add a retry span. Make
fake_modelfail the first time with aTimeoutError, and wrapcall_llmin a loop that retries once. Record the attempt number as an attribute. Show both attempts in the viewer. Hint: one span per attempt, both children ofrequest; putattempt=1andattempt=2in the attributes and let the first one end with statuserror. - Cost per request. Extend
show_trace.pyto print the total cost of the whole trace. Hint: sumcost_usdover spans that have it; do not sum therequestspan, which has none. - Find the slow tool. Make
get_ordersleep 0.4 s one time in five. Run 20 requests, then usesummarize.pyto find it. Which statistic shows the problem better, the average or the maximum, and why is neither enough? Hint: the max shows it but one outlier can be a fluke; the average blurs it. Module 11A introduces percentiles. - Scrubber gaps. Write three strings your
scrubfunction misses (a name, a phone number, an unusual key format). Decide for each whether to extend the regex or stop recording that field. Hint: a name cannot be matched reliably by a regex, so the right fix is to record less, not to match more. - A trace validator. Write
validate.pythat reads a span file and reports spans with a missingname, a negativeduration_ms, or aparent_idthat is not thespan_idof any span in the same trace. Feed it the three seeded mistakes from Part 7. Hint: build a set of(trace_id, span_id)first, then check each parent against it.
Check yourself#
- What is the difference between a trace and a span?A trace is everything for one request; a span is one timed step inside it. A trace is a tree of spans sharing a
trace_id. - Why does the recorder write its line in a
finallyblock?finallyruns whether or not the block raised, so a failed step is still recorded, and failed steps are the ones you most want. - Why does the span block yield the attributes dict instead of taking all attributes up front?Some facts (token counts, cost, finish reason) are only known after the call returns. The block adds them to the dict before the span ends.
- Name five facts to record on a model-call span.Model name, input tokens, output tokens, finish reason, latency. Cost and the provider's request id are also very useful.
- What are the three correlation ids in this lesson, and what does each one find?Your
request_idfinds every log line and span for one request;trace_idfinds every span in one trace;provider_request_idfinds the provider's own record of one call. - Why does the recorder store only the exception class and not the message?Exception messages often quote the input, which may hold secrets or personal data. The class name (for example
TimeoutError) says what kind of failure it was without leaking content. - Why is "record sizes and hashes" a stronger privacy policy than "scrub the text"?A scrubber relies on patterns, and patterns miss cases. Not recording the content means there is nothing to leak.
- What does
contextvarsdo here that a plain global variable would not?contextvarskeeps a separate "current span" per task or thread, so two requests running at once do not become each other's parents. A global would be overwritten. - Why can a span file answer "which request was expensive?" when the provider dashboard cannot?Each span carries its own request id and cost, so you can group and sort by request. The dashboard only shows totals per day, model or key.
- Name two things this recorder cannot do that Module 11A adds.It cannot export to a shared backend or use a standard schema, and it has no agent or multi-step structure beyond simple nesting.
Further resources#
- 03.10 — Logging, Debugging and Testing LLM Code: structured JSON logs, correlation ids and content flags for every call.
- 03.7 — Cost and Caching: the
usagefields per provider and how to turn them into cost. - 11A.1 — Tracing and Observability for LLM Applications: the full production treatment, including the safe exporter.
- 08A.14 — Reliable and Safe Agents: spans and trajectory replay for agents.
- OpenTelemetry — Traces concept: the standard definition of traces and spans.
- OpenAI API — Responses and Anthropic — Messages API: the
usageobjects used above.
← 03.11 — Building a Provider-Agnostic Client | 03.13 — A Minimal Eval Harness →
Going further: the Module 11A observability lesson, 11A.1 — Tracing and Observability for LLM Applications.