AI Engineering · Build lab 13 of 14

LLM tracing and cost tracking in Python with OpenTelemetry: spans, GenAI attributes, p95 latency and token budgets

Make an LLM app observable. Trace each request with OpenTelemetry (child spans for retrieval, prompt and model call), add the GenAI attributes, price every call, measure p50 and p95 latency, write JSON logs with a request id, and refuse users over a daily token budget.

⏱ 70 minIntermediate💸 Free (local model)10 steps

Python 3.12uvOllamallama3.2:3bopenai SDKOpenTelemetry SDK 1.45.2Jaeger 2 (optional, Docker)pytest

Overview video

1 / 7

0 of 10 steps done

What you will build

A small handbook assistant (retrieve a few handbook lines, build a prompt, call the model) that you can see inside. Every question becomes one trace: a root span ask with three child spans, retrieve, build_prompt and chat llama3.2:3b, each with its duration and the facts that matter (how many documents, how many tokens, which model).

Around it you add what a production LLM feature needs on day one: the standard GenAI attribute names so any tracing tool understands your spans, a cost for every request from a price table (and an honest $0 for a local model), JSON logs that carry a request id and the trace id, a per-user daily token budget that refuses a request before it reaches the model, and a small load run that reports p50 and p95 latency.

You first print spans to the terminal, then (optionally) send them to Jaeger running in Docker and look at the waterfall in a browser. Tests use an in-memory span exporter and a fake model server, so they need no model and no Docker.

Before you start

Setup

S1Install uv (the Python project tool)

uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip. Skip this if you did lab 1.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama and pull the model

Download Ollama from ollama.com/download and open it once: it serves an OpenAI-compatible API on port 11434. Then pull the small model (about 2 GB). If you did lab 1, both are already there and the pull finishes at once.

Run
ollama --version
ollama pull llama3.2:3b
You should see
ollama version is 0.x.y
pulling manifest
...
success

S4Check the model answers

Run
ollama run llama3.2:3b "Say hello in five words."
You should seeyour text will differ: the model writes it
Hello there, how are you?

S5Optional: Docker, for Jaeger in step 10

Only for the last step, where you look at traces in Jaeger's web UI. Install Docker Desktop (macOS, Windows) or Docker Engine (Linux) and start it. Everything before step 10 works without Docker.

Run
docker compose version
You should seeyour text will differ: the model writes it
Docker Compose version v2.x.y
1

Create the project

A fresh project with the SDK, OpenTelemetry and pytest, plus the settings file.

uv init creates the folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them.

New in this lab: OpenTelemetry (often shortened to OTel), the open standard for traces, metrics and logs. It comes as two packages: opentelemetry-api is what your code calls (create a span, set an attribute), opentelemetry-sdk is the engine that collects spans and sends them somewhere. It is the same split as SLF4J (API) and Logback (implementation) in Java. The OTel packages are released together, so pin them to the same version.

For the tests you add httpx2, the HTTP library the openai SDK 3.x is built on (the next major version of httpx). It has a MockTransport that lets the real SDK talk to a fake server function.

Then create the four files below. .env and config.py are lab 1's, with three new settings you will use in later steps: the provider name (for the span attributes), where spans go, and the daily token budget.

.env
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
LLM_PROVIDER=ollama

# Where spans go: console (full JSON), short (one line each), otlp (Jaeger, step 10) or none
TRACE_EXPORTER=console

# Tokens one user may spend per day (input + output), used from step 7
DAILY_TOKEN_BUDGET=20000
  1. Ollama's OpenAI-compatible API. A hosted provider needs only these first lines changed.line 2
  2. Goes into the gen_ai.provider.name span attribute (step 4). Use openai, anthropic and so on for hosted APIs.line 5
  3. Picks where finished spans go. console prints them; the others arrive in steps 4 and 10.line 8
  4. The per-user limit for the budget guard in step 7.line 11
config.py
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    provider: str
    exporter: str
    daily_token_budget: int


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
        provider=os.environ.get("LLM_PROVIDER", "ollama"),
        exporter=os.environ.get("TRACE_EXPORTER", "console"),
        daily_token_budget=int(os.environ.get("DAILY_TOKEN_BUDGET", "20000")),
    )
  1. load_dotenv() copies .env into os.environ. Real environment variables win, so TRACE_EXPORTER=short uv run ... on the command line overrides the file.line 6
  2. A read-only settings object, like a Java record.line 9
  3. Environment variables are always strings; int(...) turns the budget into a number.line 26
.gitignore
.venv/
__pycache__/
.env
usage.json
  1. Never commit .env: one day it holds a real key.line 3
  2. The token budget file from step 7: runtime data, not code.line 4
llm.py
from openai import OpenAI

from config import settings


def make_client() -> OpenAI:
    s = settings()
    return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=60, max_retries=2)
  1. A function that builds the client. Tests never call it: they build their own client pointed at a fake server.line 6
  2. The SDK retries timeouts, 429 and 5xx twice. With tracing on, each attempt is still inside one chat span.line 8
Run
uv init traced-assistant
cd traced-assistant
uv add openai python-dotenv "opentelemetry-api==1.45.2" "opentelemetry-sdk==1.45.2"
uv add --dev pytest httpx2
You should seeyour text will differ: the model writes it
Initialized project `traced-assistant` at `.../traced-assistant`
Resolved 25 packages in 520ms
Installed 21 packages in 40ms
 + openai==3.60.0
 + opentelemetry-api==1.45.2
 + opentelemetry-sdk==1.45.2
 + opentelemetry-semantic-conventions==0.66b2
 + python-dotenv==1.2.4
 ...
Why this way? OpenTelemetry is vendor-neutral: you instrument once, and the same spans can go to the console, Jaeger, Grafana Tempo, Honeycomb, Datadog or Langfuse by changing the exporter, not your code. That is why it is the default choice for tracing LLM apps.
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
uv also created main.py
Newer uv versions write a hello-world main.py. This lab does not use it: delete it or leave it.
zsh: no matches found: opentelemetry-api==...
Keep the double quotes around each "package==version" exactly as shown; without them some shells try to read == as a pattern.
2

The app you will observe

A working handbook assistant with no tracing yet: retrieve, build the prompt, call the model.

Tracing only makes sense on a program with several stages, so first build one. It is a mini RAG app (see the RAG lab for the real thing): retrieve() picks the handbook lines that share the most words with the question, build_prompt() puts them into the messages, and the model answers from them.

Assistant is a class that receives its dependencies in the constructor (the client and the model name), the same idea as constructor injection in Spring. Later steps add a tracer and a budget the same way, and the tests pass in fakes.

Each request gets a request id: 12 random hex characters. You will see it on the answer line now, and on spans and log lines later, so one id finds everything about one request.

docs.py
# A tiny company handbook. In lab 6 this came from a vector database; here a list is enough.
DOCS = [
    {"id": "holiday", "text": "Employees get 25 days of paid holiday a year. Unused days expire on 31 March."},
    {"id": "parental", "text": "Parental leave is 16 weeks at full pay for every new parent."},
    {"id": "remote", "text": "You can work remotely up to three days a week. Agree the days with your manager."},
    {"id": "expenses", "text": "Submit expenses within 30 days. Meals on business trips are covered up to 40 euros a day."},
    {"id": "laptop", "text": "Every employee gets a laptop. Report a lost laptop to IT within 24 hours."},
]
  1. A list of dicts, like a List<Map<String, String>>. Five handbook facts the model may answer from.line 2
rag.py
from docs import DOCS

STOP = {"a", "an", "the", "is", "are", "do", "i", "you", "how", "what", "many", "of", "to", "my", "get", "for", "on", "in"}
SYSTEM = "Answer in one or two sentences, using only the context. If the context does not say, reply: I don't know."


def words(text: str) -> set[str]:
    return {w.strip(".,?!:").lower() for w in text.split()} - STOP


def retrieve(question: str, k: int = 2) -> list[dict]:
    """The k handbook entries that share the most words with the question."""
    q = words(question)
    scored = sorted(DOCS, key=lambda d: len(q & words(d["text"])), reverse=True)
    return [d for d in scored[:k] if q & words(d["text"])]


def build_prompt(question: str, docs: list[dict]) -> list[dict]:
    context = "\n".join(f"- {d['text']}" for d in docs) or "(nothing found)"
    return [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
    ]
  1. A set of common words to ignore, so "how" and "the" do not count as matches.line 3
  2. Lower-case words without punctuation, minus the stop words. {... for w in ...} is a set comprehension; - on sets is "remove these", like removeAll.line 7
  3. q & words(...) is the set intersection (shared words). Sort by how many are shared, most first. key=lambda d: ... is like a Comparator.comparing(d -> ...).line 14
  4. The top k, but only entries that share at least one word (an empty set counts as false).line 15
  5. "\n".join(...) puts one entry per line. or "(nothing found)" gives the model something honest to read when nothing matched.line 19
app.py
import time
import uuid
from dataclasses import dataclass

from rag import build_prompt, retrieve


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str):
        self.client = client
        self.model = model

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        docs = retrieve(question)
        messages = build_prompt(question, docs)
        resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
        usage = resp.usage
        latency_ms = (time.perf_counter() - start) * 1000
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, latency_ms)
  1. The result of one request: what the caller prints now and what the tests check later.line 8
  2. Dependencies come in through the constructor. self.client = client is this.client = client.line 18
  3. uuid4().hex is 32 random hex characters; [:12] keeps the first 12, short enough to read and unique enough for a lab.line 23
  4. perf_counter() is a high-resolution clock for measuring durations, like System.nanoTime(). Never use wall-clock time for latency.line 24
  5. The same SDK call as lab 1, now with the retrieved context in messages.line 27
  6. End minus start is seconds as a float; times 1000 gives milliseconds.line 29
ask.py
import argparse
import sys

import openai

from app import Assistant
from config import settings
from llm import make_client


def main() -> None:
    parser = argparse.ArgumentParser(description="Ask the handbook assistant a question.")
    parser.add_argument("question", nargs="+")
    parser.add_argument("--user", default="anonymous")
    args = parser.parse_args()

    s = settings()
    bot = Assistant(make_client(), s.model)
    try:
        r = bot.ask(" ".join(args.question), user=args.user)
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try a shorter question or a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")

    print(r.answer)
    print(f"[request {r.request_id}] {r.input_tokens} in, {r.output_tokens} out, {r.latency_ms:.0f} ms")


if __name__ == "__main__":
    main()
  1. argparse is Python's built-in command-line parser (like picocli in Java or yargs in Node). It also generates --help.line 12
  2. One or more words: uv run ask.py How long is leave works without quotes, the words are joined on the next lines.line 13
  3. An optional flag with a default. Read it as args.user.line 14
  4. Timeout first: it is a subclass of APIConnectionError, and Python uses the first except that matches.line 21
  5. True only when you run this file directly (uv run ask.py), not when another file imports it. It is Python's public static void main.line 30
Run
uv run ask.py "How many days of holiday do I get?"
You should seeyour text will differ: the model writes it
Employees get 25 days of paid holiday a year, and unused days expire on 31 March.
[request 3f9c2a7d41b0] 112 in, 21 out, 1840 ms
Why this way? Right now you know the total time and nothing else. Was it the retrieval, a slow model, or a retry? On one laptop you can guess; in production with thousands of requests a minute you cannot. That is the question tracing answers.
Stuck on this step?
Cannot reach the model server
Ollama is not running. Open the Ollama app or run ollama serve, then try again.
The first call takes 10 seconds or more
Normal: Ollama loads the model into memory on the first call. Run it again and it is much faster. Remember this: in step 8 you will see it as a slow p95.
The answer is "I don't know"
The question shared no words with the handbook, so the context said "(nothing found)". Ask about holiday, parental leave, remote work, expenses or laptops.
3

Your first trace, printed to the console

One trace per request: a root span with child spans for retrieve, build_prompt and the model call.

Four words you need. A span is one timed operation with a name, a start and end time, and attributes (key-value facts). A trace is all the spans of one request, linked as a tree: each span knows its parent. A tracer creates spans. An exporter sends finished spans somewhere.

tracing.py sets up the SDK once at program start: a TracerProvider (the factory for tracers) with a resource (who is sending: service.name is how your app shows up in any tracing UI), and a span processor that hands each finished span to an exporter. ConsoleSpanExporter prints spans as JSON, perfect to see exactly what a span contains.

In app.py, with tracer.start_as_current_span("ask") as span: opens a span and ends it when the with block ends, even if an exception is thrown (like try-with-resources in Java). "Current" matters: a span started inside that block automatically becomes its child, so the nesting of with blocks becomes the tree. No ids to pass around.

tracing.py
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor


def setup_tracing(exporter: str, service_name: str = "traced-assistant") -> TracerProvider:
    provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
    if exporter == "console":
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
    elif exporter != "none":
        raise ValueError(f"unknown TRACE_EXPORTER {exporter!r}: use console or none")
    trace.set_tracer_provider(provider)
    return provider
  1. trace is the API package: what your code and libraries call. The sdk imports below are the engine.line 1
  2. service.name names your app in every trace. Resource.create also adds SDK facts like the language and SDK version.line 8
  3. SimpleSpanProcessor exports each span the moment it ends, one at a time. Fine for the console and tests; step 10 uses a batching processor for the network.line 10
  4. none means "make spans, send them nowhere": useful for the load run. Any other word is a typo, so fail loudly.line 11
  5. Makes this provider the global one, so libraries that use the OpenTelemetry API find it. Call it once, at startup.line 13
app.py 14 new or changed lines
import time
import uuid
from dataclasses import dataclass

from rag import build_prompt, retrieve


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str, tracer):
        self.client = client
        self.model = model
        self.tracer = tracer

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        with self.tracer.start_as_current_span("ask") as span:
            span.set_attribute("app.request_id", request_id)
            span.set_attribute("app.user", user)
            with self.tracer.start_as_current_span("retrieve") as s:
                docs = retrieve(question)
                s.set_attribute("app.retrieve.count", len(docs))
            with self.tracer.start_as_current_span("build_prompt"):
                messages = build_prompt(question, docs)
            with self.tracer.start_as_current_span("chat"):
                resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
            usage = resp.usage
            latency_ms = (time.perf_counter() - start) * 1000
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, latency_ms)
  1. The tracer is injected like the client. The tests in step 9 pass a tracer that writes to memory.line 18
  2. The root span: everything about this request happens inside it. as span gives you the span object to add attributes to.line 26
  3. Attributes are searchable key-value facts. Your own attributes get a prefix like app. so they never clash with standard names.line 27
  4. A child span: it starts inside the ask block, so its parent is ask. as s because span is already taken.line 29
  5. How many entries were found. When an answer is bad, the first question is "did retrieval find anything?" and now the trace tells you.line 31
  6. The model call gets its own span: in a real app this is nearly all of the time. Step 4 gives it a standard name and attributes.line 34
ask.py 5 new or changed lines
import argparse
import sys

import openai

from app import Assistant
from config import settings
from llm import make_client
from tracing import setup_tracing


def main() -> None:
    parser = argparse.ArgumentParser(description="Ask the handbook assistant a question.")
    parser.add_argument("question", nargs="+")
    parser.add_argument("--user", default="anonymous")
    args = parser.parse_args()

    s = settings()
    tracer_provider = setup_tracing(s.exporter)
    bot = Assistant(make_client(), s.model, tracer_provider.get_tracer("assistant"))
    try:
        r = bot.ask(" ".join(args.question), user=args.user)
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try a shorter question or a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
    finally:
        tracer_provider.shutdown()

    print(r.answer)
    print(f"[request {r.request_id}] {r.input_tokens} in, {r.output_tokens} out, {r.latency_ms:.0f} ms")


if __name__ == "__main__":
    main()
  1. Set up tracing once, before anything makes a span.line 19
  2. A tracer named after the code that uses it (the "instrumentation scope"), like a logger name.line 20
  3. finally runs on success, on an exception and on sys.exit(). shutdown() flushes spans that are still waiting, so none are lost when the program ends.line 27
Run
uv run ask.py "How long is parental leave?"
You should seeyour text will differ: the model writes it
{
    "name": "retrieve",
    "context": {
        "trace_id": "0x3cbc3b56ac1024e78153d8450b902922",
        "span_id": "0xc5ffa6af0db8c95c",
        "trace_state": "[]"
    },
    "kind": "SpanKind.INTERNAL",
    "parent_id": "0x38e73d0eab2be207",
    "start_time": "2026-11-29T06:35:38.761858Z",
    "end_time": "2026-11-29T06:35:38.761943Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {
        "app.retrieve.count": 1
    },
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.45.2",
            "service.instance.id": "9400a09b-0ca5-4de5-ad6a-76424f118f2e",
            "service.name": "traced-assistant"
        },
        "schema_url": ""
    }
}
{
    "name": "build_prompt",
    ...
}
{
    "name": "chat",
    ...
}
{
    "name": "ask",
    "context": {
        "trace_id": "0x3cbc3b56ac1024e78153d8450b902922",
        "span_id": "0x38e73d0eab2be207",
        ...
    },
    "parent_id": null,
    ...
}
Parental leave is 16 weeks at full pay for every new parent.
[request 8d01c6e2f7a4] 98 in, 14 out, 1210 ms
Why this way? Read the ids: all four spans have the same trace_id, and the parent_id of retrieve, build_prompt and chat is the span_id of ask, whose own parent_id is null (the root). Spans print in the order they end, so children come before their parent. status_code is UNSET, which means "nothing went wrong"; an exception makes it ERROR.
Stuck on this step?
ModuleNotFoundError: No module named 'opentelemetry.sdk'
Only the API package is installed. Run uv add "opentelemetry-sdk==1.45.2", keeping the same version as opentelemetry-api.
Overriding of current TracerProvider is not allowed
Something called setup_tracing() twice in one process. Call it once at startup; tests build their own TracerProvider without making it global.
No spans are printed
Check TRACE_EXPORTER=console in .env and that the shell does not override it (echo $TRACE_EXPORTER).
4

Standard GenAI attributes on the model span

Name and describe the model call the way every tracing tool expects: the OpenTelemetry GenAI semantic conventions.

Semantic conventions are agreed attribute names, so tools understand your spans without configuration. For HTTP there is http.request.method; for LLM calls there are the GenAI conventions, with names that start with gen_ai.. LLM-aware backends such as Datadog, Langfuse, Arize Phoenix and Grafana use them to show token counts and models (Jaeger simply lists them with the other attributes). The conventions are still marked "development" (they can change), and they recently moved to their own repository, open-telemetry/semantic-conventions-genai; the names below are the current ones.

The rules for a model call span: name it {operation} {model} (here chat llama3.2:3b), make it kind CLIENT (your app calls an outside service), and set gen_ai.operation.name, gen_ai.provider.name and gen_ai.request.model before the call, then gen_ai.response.model, gen_ai.response.finish_reasons, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens from the response. On failure, set error.type. (Older code uses gen_ai.system and gen_ai.usage.prompt_tokens: those names are deprecated.)

The opentelemetry-semantic-conventions package has Python constants for these names, but the GenAI ones live in a private _incubating module and are marked deprecated since the move. Plain strings are clearer and do not warn.

The full JSON is too long to read every time, so tracing.py gets a second console format, short: one line per span.

app.py 19 new or changed lines
import time
import uuid
from dataclasses import dataclass

from opentelemetry.trace import SpanKind

from rag import build_prompt, retrieve


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str, tracer, provider: str):
        self.client = client
        self.model = model
        self.tracer = tracer
        self.provider = provider

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        with self.tracer.start_as_current_span("ask") as span:
            span.set_attribute("app.request_id", request_id)
            span.set_attribute("app.user", user)
            with self.tracer.start_as_current_span("retrieve") as s:
                docs = retrieve(question)
                s.set_attribute("app.retrieve.count", len(docs))
            with self.tracer.start_as_current_span("build_prompt"):
                messages = build_prompt(question, docs)
            resp = self._chat(messages)
            usage = resp.usage
            latency_ms = (time.perf_counter() - start) * 1000
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, latency_ms)

    def _chat(self, messages: list[dict]):
        with self.tracer.start_as_current_span(f"chat {self.model}", kind=SpanKind.CLIENT) as span:
            span.set_attribute("gen_ai.operation.name", "chat")
            span.set_attribute("gen_ai.provider.name", self.provider)
            span.set_attribute("gen_ai.request.model", self.model)
            span.set_attribute("gen_ai.request.temperature", 0.2)
            try:
                resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
            except Exception as e:
                span.set_attribute("error.type", type(e).__name__)
                raise
            span.set_attribute("gen_ai.response.model", resp.model)
            span.set_attribute("gen_ai.response.finish_reasons", [resp.choices[0].finish_reason])
            span.set_attribute("gen_ai.usage.input_tokens", resp.usage.prompt_tokens)
            span.set_attribute("gen_ai.usage.output_tokens", resp.usage.completion_tokens)
            return resp
  1. SpanKind says what role a span plays: INTERNAL (the default), CLIENT (calls out), SERVER (handles a request), and others.line 5
  2. Who serves the model: ollama here. It goes on the span, not into the API call.line 20
  3. The model call moves into its own method, which owns its span.line 37
  4. The conventional span name: operation, a space, the model. Searching for chat llama3.2:3b in a UI finds every call to that model.line 44
  5. CLIENT, because the model runs in another process (Ollama) or another company.line 44
  6. chat for chat completions. Other values include embeddings, execute_tool and invoke_agent.line 45
  7. Catch, label, re-raise. The with block already records the exception and sets the status to ERROR; error.type adds the short class name that dashboards group by.line 51
  8. The class name of the exception, like e.getClass().getSimpleName(), for example APIConnectionError.line 52
  9. The model that really answered. Hosted APIs often return a dated version here (the request said one name, the response says the exact build).line 54
  10. A list, because one request can ask for several answers. stop is normal; length means the answer was cut off.line 55
  11. The token counts from usage: your bill. prompt_tokens in the SDK is input_tokens in the conventions.line 56
tracing.py 11 new or changed lines
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor


def one_line(span: ReadableSpan) -> str:
    """A short console format: name, duration, status, the start of the trace id, attributes."""
    ms = (span.end_time - span.start_time) / 1_000_000
    status = span.status.status_code.name
    trace_id = format(span.context.trace_id, "032x")[:8]
    attrs = " ".join(f"{k}={v}" for k, v in span.attributes.items())
    return f"{span.name:<18} {ms:7.1f} ms  {status:<5}  trace={trace_id}  {attrs}\n"


def setup_tracing(exporter: str, service_name: str = "traced-assistant") -> TracerProvider:
    provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
    if exporter == "console":
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
    elif exporter == "short":
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
    elif exporter != "none":
        raise ValueError(f"unknown TRACE_EXPORTER {exporter!r}: use console, short or none")
    trace.set_tracer_provider(provider)
    return provider
  1. A formatter: a function from a finished span to text. ConsoleSpanExporter calls it for each span.line 7
  2. Span times are integers in nanoseconds since 1970. Dividing the difference by a million gives milliseconds.line 9
  3. UNSET, OK or ERROR. .name gives the enum constant's name, like Enum.name() in Java.line 10
  4. The trace id is a 128-bit integer. "032x" writes it as 32 hex digits with leading zeros; [:8] keeps the start, enough to see which spans belong together.line 11
  5. :<18 pads to 18 characters, left-aligned, so the columns line up.line 13
  6. Pass the function itself (no parentheses), like a method reference Tracing::oneLine.line 21
ask.py 1 new line
import argparse
import sys

import openai

from app import Assistant
from config import settings
from llm import make_client
from tracing import setup_tracing


def main() -> None:
    parser = argparse.ArgumentParser(description="Ask the handbook assistant a question.")
    parser.add_argument("question", nargs="+")
    parser.add_argument("--user", default="anonymous")
    args = parser.parse_args()

    s = settings()
    tracer_provider = setup_tracing(s.exporter)
    bot = Assistant(make_client(), s.model, tracer_provider.get_tracer("assistant"), provider=s.provider)
    try:
        r = bot.ask(" ".join(args.question), user=args.user)
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try a shorter question or a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
    finally:
        tracer_provider.shutdown()

    print(r.answer)
    print(f"[request {r.request_id}] {r.input_tokens} in, {r.output_tokens} out, {r.latency_ms:.0f} ms")


if __name__ == "__main__":
    main()
  1. Passed by name: easier to read than a fourth positional argument.line 20
Run
TRACE_EXPORTER=short uv run ask.py "How long is parental leave?"
You should seeyour text will differ: the model writes it
retrieve               0.0 ms  UNSET  trace=9d40269f  app.retrieve.count=1
build_prompt           0.0 ms  UNSET  trace=9d40269f
chat llama3.2:3b      384.5 ms  UNSET  trace=9d40269f  gen_ai.operation.name=chat gen_ai.provider.name=ollama gen_ai.request.model=llama3.2:3b gen_ai.request.temperature=0.2 gen_ai.response.model=llama3.2:3b gen_ai.response.finish_reasons=('stop',) gen_ai.usage.input_tokens=77 gen_ai.usage.output_tokens=9
ask                  385.9 ms  UNSET  trace=9d40269f  app.request_id=383a2f90b028 app.user=anonymous
Parental leave is 16 weeks.
[request 383a2f90b028] 77 in, 9 out, 385 ms
Why this way? Now the answer to "where did the time go?" is on screen: retrieval and prompt building take a fraction of a millisecond, the model call is almost all of the request. That is typical, and it tells you where optimizing pays off (a smaller model, a shorter prompt, caching), and where it does not.
Stuck on this step?
Windows: TRACE_EXPORTER=short uv run ... is not recognised
In PowerShell run $env:TRACE_EXPORTER="short"; uv run ask.py "How long is parental leave?", and Remove-Item Env:TRACE_EXPORTER afterwards. Or change the line in .env.
finish_reasons=('stop',) has round brackets
Correct. The SDK stores list attributes as tuples (read-only lists). ('stop',) is a tuple with one item.
5

Cost per request from a price table

Every request knows what it cost, with $0 for local models and no silent guesses for unknown ones.

Token counts become money with a price table: dollars per million input tokens and per million output tokens (output usually costs several times more). The hosted prices below are examples; put your provider's real prices in PRICES.

Local models are in the table at (0.0, 0.0) on purpose. Lab 1 returned 0 for any unknown model; that is convenient but dangerous: switch .env to a new hosted model, forget the table, and every dashboard says "free". Here an unknown model returns None ("no price"), and the output says so.

The cost goes on the root span as app.cost_usd. There is no GenAI convention for cost (prices are not in the response), so it gets your app. prefix.

cost.py
# US dollars per 1 million tokens: (input, output). The hosted rows are EXAMPLES:
# put your provider's real prices here. Local models cost nothing per call.
PRICES = {
    "llama3.2:3b": (0.0, 0.0),
    "llama3.2:1b": (0.0, 0.0),
    "small-model": (0.15, 0.60),
    "frontier-model": (3.00, 15.00),
}


def cost_usd(model: str, input_tokens: int, output_tokens: int) -> float | None:
    """Dollar cost of one call, or None when the model has no price (never guess 0)."""
    price = PRICES.get(model)
    if price is None:
        return None
    price_in, price_out = price
    return (input_tokens * price_in + output_tokens * price_out) / 1_000_000


def usd(amount: float | None) -> str:
    return "unknown (add the model to PRICES)" if amount is None else f"${amount:.6f}"
  1. A dict from model name to a tuple (input price, output price). A tuple is a fixed-size, read-only list.line 3
  2. Local models: no per-call price. (Your laptop's electricity and a GPU server's rent are real, but they do not grow with each token.)line 4
  3. The return type is "a float or None", like Optional<Double>. The | syntax for types is Python 3.10+.line 11
  4. Tuple unpacking: two variables from a two-item tuple in one line.line 16
  5. Prices are per million tokens. Underscores in numbers are only for readability.line 17
  6. Formats the amount with six decimals, because one local-sized call costs fractions of a cent on hosted models.line 20
app.py 6 new or changed lines
import time
import uuid
from dataclasses import dataclass

from opentelemetry.trace import SpanKind

from cost import cost_usd
from rag import build_prompt, retrieve


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    cost_usd: float | None
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str, tracer, provider: str):
        self.client = client
        self.model = model
        self.tracer = tracer
        self.provider = provider

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        with self.tracer.start_as_current_span("ask") as span:
            span.set_attribute("app.request_id", request_id)
            span.set_attribute("app.user", user)
            with self.tracer.start_as_current_span("retrieve") as s:
                docs = retrieve(question)
                s.set_attribute("app.retrieve.count", len(docs))
            with self.tracer.start_as_current_span("build_prompt"):
                messages = build_prompt(question, docs)
            resp = self._chat(messages)
            usage = resp.usage
            cost = cost_usd(self.model, usage.prompt_tokens, usage.completion_tokens)
            if cost is not None:
                span.set_attribute("app.cost_usd", cost)
            latency_ms = (time.perf_counter() - start) * 1000
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, cost, latency_ms)

    def _chat(self, messages: list[dict]):
        with self.tracer.start_as_current_span(f"chat {self.model}", kind=SpanKind.CLIENT) as span:
            span.set_attribute("gen_ai.operation.name", "chat")
            span.set_attribute("gen_ai.provider.name", self.provider)
            span.set_attribute("gen_ai.request.model", self.model)
            span.set_attribute("gen_ai.request.temperature", 0.2)
            try:
                resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
            except Exception as e:
                span.set_attribute("error.type", type(e).__name__)
                raise
            span.set_attribute("gen_ai.response.model", resp.model)
            span.set_attribute("gen_ai.response.finish_reasons", [resp.choices[0].finish_reason])
            span.set_attribute("gen_ai.usage.input_tokens", resp.usage.prompt_tokens)
            span.set_attribute("gen_ai.usage.output_tokens", resp.usage.completion_tokens)
            return resp
  1. The result now carries the cost (or None if the model has no price).line 17
  2. Priced by the model you **asked for**: a dated name in resp.model would not be in the table.line 41
  3. Span attributes cannot be None, so set it only when there is a price. is not None is the safe test: if cost: would also skip a real 0.0.line 42
ask.py 5 new or changed lines
import argparse
import sys

import openai

from app import Assistant
from config import settings
from cost import cost_usd, usd
from llm import make_client
from tracing import setup_tracing


def main() -> None:
    parser = argparse.ArgumentParser(description="Ask the handbook assistant a question.")
    parser.add_argument("question", nargs="+")
    parser.add_argument("--user", default="anonymous")
    args = parser.parse_args()

    s = settings()
    tracer_provider = setup_tracing(s.exporter)
    bot = Assistant(make_client(), s.model, tracer_provider.get_tracer("assistant"), provider=s.provider)
    try:
        r = bot.ask(" ".join(args.question), user=args.user)
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try a shorter question or a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
    finally:
        tracer_provider.shutdown()

    print(r.answer)
    print(f"[request {r.request_id}] {r.input_tokens} in, {r.output_tokens} out, "
          f"cost {usd(r.cost_usd)}, {r.latency_ms:.0f} ms")
    for name in ("small-model", "frontier-model"):
        print(f"  the same call on {name}: {usd(cost_usd(name, r.input_tokens, r.output_tokens))}")


if __name__ == "__main__":
    main()
  1. Two f-strings next to each other inside print(...) join into one line.line 33
  2. The same tokens priced on the example hosted models: what this request would cost if you moved off the laptop.line 34
Run
TRACE_EXPORTER=none uv run ask.py "How many days a week can I work remotely?"
You should seeyour text will differ: the model writes it
You can work remotely up to three days a week, after agreeing the days with your manager.
[request c4b794cfc2a8] 104 in, 19 out, cost $0.000000, 1390 ms
  the same call on small-model: $0.000027
  the same call on frontier-model: $0.000597
Why this way? Cost per request is the number product decisions need ("can we offer this to free users?"), and it only exists if you compute it at the moment you have the token counts. Afterwards, the usage is gone.
Stuck on this step?
It says cost unknown (add the model to PRICES)
That is the guard working: your LLM_MODEL is not in PRICES. Add a row with its prices (or (0.0, 0.0) for another local model).
6

Structured JSON logs with the request id

One JSON log line per request, with the request id and the trace id, ready for any log search tool.

Traces show the shape of a request; logs record events. In production both go to tools that search them, and tools search JSON far better than free text: user = "alice" and cost_usd > 0.01 is a query, not a regex.

Python's logging module works like Java's SLF4J/Logback: you get a named logger, attach a handler (where lines go) with a formatter (what a line looks like). JsonFormatter writes one JSON object per line. It also adds the trace id of the span that is current when you log, so from any log line you can jump to its trace, and back.

Extra fields travel on the log record. log.info("request finished", extra={"fields": {...}}) attaches a fields attribute to the record, and the formatter copies it into the JSON. Logs go to stderr, so they do not mix with the answer on stdout (you can send them to a file with 2> app.log).

logs.py
import json
import logging
import sys
from datetime import datetime, timezone

from opentelemetry import trace


class JsonFormatter(logging.Formatter):
    """One JSON object per line, with the current trace id so logs and traces link up."""

    def format(self, record: logging.LogRecord) -> str:
        entry = {
            "ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
            "level": record.levelname,
            "msg": record.getMessage(),
        }
        ctx = trace.get_current_span().get_span_context()
        if ctx.is_valid:
            entry["trace_id"] = format(ctx.trace_id, "032x")
        entry.update(getattr(record, "fields", {}))
        return json.dumps(entry)


def get_logger(name: str = "assistant") -> logging.Logger:
    logger = logging.getLogger(name)
    if not logger.handlers:
        handler = logging.StreamHandler(sys.stderr)
        handler.setFormatter(JsonFormatter())
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        logger.propagate = False
    return logger
  1. Subclass the standard formatter and override format(), the one method that turns a record into text.line 9
  2. The time the log call happened, in seconds since 1970. Written in UTC with milliseconds, an ISO 8601 string every tool can parse.line 14
  3. The message with any %s arguments filled in.line 16
  4. The span that is current right now (the innermost open with block). Outside any span you get a placeholder whose context is not valid.line 18
  5. The same 32-hex-digit form Jaeger shows, so you can paste it into Jaeger's search box.line 20
  6. The fields attribute if the caller passed one, otherwise an empty dict. Like Optional.ofNullable(x).orElse(Map.of()).line 21
  7. Add the handler only once, even if get_logger() is called many times (every handler would print each line again).line 27
  8. Do not also pass records up to the root logger, which might print them a second time in another format.line 32
app.py 7 new or changed lines
import time
import uuid
from dataclasses import dataclass

from opentelemetry.trace import SpanKind

from cost import cost_usd
from logs import get_logger
from rag import build_prompt, retrieve

log = get_logger()


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    cost_usd: float | None
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str, tracer, provider: str):
        self.client = client
        self.model = model
        self.tracer = tracer
        self.provider = provider

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        with self.tracer.start_as_current_span("ask") as span:
            span.set_attribute("app.request_id", request_id)
            span.set_attribute("app.user", user)
            with self.tracer.start_as_current_span("retrieve") as s:
                docs = retrieve(question)
                s.set_attribute("app.retrieve.count", len(docs))
            with self.tracer.start_as_current_span("build_prompt"):
                messages = build_prompt(question, docs)
            resp = self._chat(messages)
            usage = resp.usage
            cost = cost_usd(self.model, usage.prompt_tokens, usage.completion_tokens)
            if cost is not None:
                span.set_attribute("app.cost_usd", cost)
            latency_ms = (time.perf_counter() - start) * 1000
            log.info("request finished", extra={"fields": {
                "request_id": request_id, "user": user, "model": self.model,
                "input_tokens": usage.prompt_tokens, "output_tokens": usage.completion_tokens,
                "cost_usd": cost, "latency_ms": round(latency_ms, 1),
            }})
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, cost, latency_ms)

    def _chat(self, messages: list[dict]):
        with self.tracer.start_as_current_span(f"chat {self.model}", kind=SpanKind.CLIENT) as span:
            span.set_attribute("gen_ai.operation.name", "chat")
            span.set_attribute("gen_ai.provider.name", self.provider)
            span.set_attribute("gen_ai.request.model", self.model)
            span.set_attribute("gen_ai.request.temperature", 0.2)
            try:
                resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
            except Exception as e:
                span.set_attribute("error.type", type(e).__name__)
                raise
            span.set_attribute("gen_ai.response.model", resp.model)
            span.set_attribute("gen_ai.response.finish_reasons", [resp.choices[0].finish_reason])
            span.set_attribute("gen_ai.usage.input_tokens", resp.usage.prompt_tokens)
            span.set_attribute("gen_ai.usage.output_tokens", resp.usage.completion_tokens)
            return resp
  1. One logger for the module, created at import time, like a private static final Logger.line 11
  2. Logged **inside** the ask span, so the formatter finds its trace id. The message is fixed; the facts go in fields, so every line of this kind has the same shape.line 48
  3. One decimal is plenty for milliseconds and keeps the log line short.line 51
Run
TRACE_EXPORTER=none uv run ask.py --user alice "How many days of holiday do I get?"
You should seeyour text will differ: the model writes it
{"ts": "2026-11-29T06:35:32.089+00:00", "level": "INFO", "msg": "request finished", "trace_id": "a45179b29ad6e325a4cbc6a422189083", "request_id": "c4b794cfc2a8", "user": "alice", "model": "llama3.2:3b", "input_tokens": 112, "output_tokens": 21, "cost_usd": 0.0, "latency_ms": 1840.2}
Employees get 25 days of paid holiday a year, and unused days expire on 31 March.
[request c4b794cfc2a8] 112 in, 21 out, cost $0.000000, 1840 ms
  the same call on small-model: $0.000029
  the same call on frontier-model: $0.000651
Why this way? The request id is for people ("my request c4b794cfc2a8 gave a weird answer"), the trace id is for tools. Logging both on the same line links a support ticket, a log search and a trace waterfall. Never log the prompt or the answer by default: they can contain personal data. Log sizes and counts instead.
Stuck on this step?
The log line has no trace_id
The log.info(...) call is outside the with ... ("ask") block. Indent it so it runs while the span is open.
Every log line appears twice
Something else (a framework, or logging.basicConfig()) added a root handler. Keep logger.propagate = False in get_logger().
7

A per-user daily token budget

Refuse a request before it reaches the model when the user would go over today's token limit.

A single user (or a bug in a loop) can spend your whole monthly budget in an afternoon. The fix is a budget guard: count tokens per user per day, and refuse before the model call when the next request could push them over the limit.

You need the token count before the call, when there is no usage yet. So estimate_tokens() makes a rough estimate: about 4 characters per token for English text. It is only an estimate (other languages and code use more tokens per character); after the call, the guard records the real usage numbers.

The counts live in memory and in usage.json, keyed by date and user (2026-11-29:alice), so the limit survives a restart and resets the next day on its own. A lock protects the counts because the load run in step 8 uses several threads.

A refused request is still a traced request: the ask span gets app.refused=budget and status ERROR (the exception passes through the with block), and a WARNING log line says why.

budget.py
import json
import threading
from datetime import date
from pathlib import Path


class BudgetExceeded(Exception):
    def __init__(self, user: str, used: int, needed: int, limit: int):
        super().__init__(f"{user} has used {used} of {limit} tokens today and this request needs about {needed}")
        self.user, self.used, self.needed, self.limit = user, used, needed, limit


def estimate_tokens(messages: list[dict]) -> int:
    """A rough count before the call: about 4 characters per token in English text."""
    return sum(len(m["content"]) for m in messages) // 4 + 1


class TokenBudget:
    """Tokens used per user per day, optionally saved to a JSON file."""

    def __init__(self, daily_limit: int, path: str | None = None, today=date.today):
        self.daily_limit = daily_limit
        self.path = Path(path) if path else None
        self.today = today
        self._lock = threading.Lock()
        self._used: dict[str, int] = {}
        if self.path and self.path.exists():
            self._used = json.loads(self.path.read_text())

    def _key(self, user: str) -> str:
        return f"{self.today().isoformat()}:{user}"

    def used(self, user: str) -> int:
        with self._lock:
            return self._used.get(self._key(user), 0)

    def check(self, user: str, estimated: int) -> None:
        """Raise BudgetExceeded if this call could take the user over today's limit."""
        used = self.used(user)
        if used + estimated > self.daily_limit:
            raise BudgetExceeded(user, used, estimated, self.daily_limit)

    def record(self, user: str, tokens: int) -> None:
        with self._lock:
            key = self._key(user)
            self._used[key] = self._used.get(key, 0) + tokens
            if self.path:
                self.path.write_text(json.dumps(self._used, indent=2))
  1. A custom exception carrying the numbers, so the caller can show a helpful message.line 7
  2. Several assignments in one line: each name on the left gets the value in the same position on the right.line 10
  3. // is integer division (/ in Java on ints). + 1 so even an empty prompt counts as at least one token.line 15
  4. The **function** date.today (no parentheses) is the default. Tests pass their own function returning a fixed date, so "tomorrow" can be tested today.line 21
  5. A mutex, like ReentrantLock without the reentrant part. with self._lock: acquires it and always releases it.line 25
  6. Load yesterday's and today's counts from the file, if it exists.line 28
  7. One key per day and user, such as 2026-11-29:alice. A new day means a new key starting at 0.line 31
  8. Refuse if this request **could** cross the limit. Checking only used >= limit would let one huge request go far over.line 40
  9. .get(key, 0) is getOrDefault(key, 0).line 46
  10. Save after every request. Fine for one process; several servers need a shared store (see In production).line 48
app.py 11 new or changed lines
import time
import uuid
from dataclasses import dataclass

from opentelemetry.trace import SpanKind

from budget import BudgetExceeded, TokenBudget, estimate_tokens
from cost import cost_usd
from logs import get_logger
from rag import build_prompt, retrieve

log = get_logger()


@dataclass
class Result:
    request_id: str
    answer: str
    input_tokens: int
    output_tokens: int
    cost_usd: float | None
    latency_ms: float


class Assistant:
    def __init__(self, client, model: str, tracer, provider: str, budget: TokenBudget):
        self.client = client
        self.model = model
        self.tracer = tracer
        self.provider = provider
        self.budget = budget

    def ask(self, question: str, user: str = "anonymous") -> Result:
        request_id = uuid.uuid4().hex[:12]
        start = time.perf_counter()
        with self.tracer.start_as_current_span("ask") as span:
            span.set_attribute("app.request_id", request_id)
            span.set_attribute("app.user", user)
            with self.tracer.start_as_current_span("retrieve") as s:
                docs = retrieve(question)
                s.set_attribute("app.retrieve.count", len(docs))
            with self.tracer.start_as_current_span("build_prompt") as s:
                messages = build_prompt(question, docs)
                estimate = estimate_tokens(messages)
                s.set_attribute("app.prompt.estimated_tokens", estimate)
            try:
                self.budget.check(user, estimate)
            except BudgetExceeded:
                span.set_attribute("app.refused", "budget")
                log.warning("request refused", extra={"fields": {"request_id": request_id, "user": user, "reason": "budget"}})
                raise
            resp = self._chat(messages)
            usage = resp.usage
            self.budget.record(user, usage.prompt_tokens + usage.completion_tokens)
            cost = cost_usd(self.model, usage.prompt_tokens, usage.completion_tokens)
            if cost is not None:
                span.set_attribute("app.cost_usd", cost)
            latency_ms = (time.perf_counter() - start) * 1000
            log.info("request finished", extra={"fields": {
                "request_id": request_id, "user": user, "model": self.model,
                "input_tokens": usage.prompt_tokens, "output_tokens": usage.completion_tokens,
                "cost_usd": cost, "latency_ms": round(latency_ms, 1),
            }})
        return Result(request_id, resp.choices[0].message.content or "", usage.prompt_tokens,
                      usage.completion_tokens, cost, latency_ms)

    def _chat(self, messages: list[dict]):
        with self.tracer.start_as_current_span(f"chat {self.model}", kind=SpanKind.CLIENT) as span:
            span.set_attribute("gen_ai.operation.name", "chat")
            span.set_attribute("gen_ai.provider.name", self.provider)
            span.set_attribute("gen_ai.request.model", self.model)
            span.set_attribute("gen_ai.request.temperature", 0.2)
            try:
                resp = self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.2)
            except Exception as e:
                span.set_attribute("error.type", type(e).__name__)
                raise
            span.set_attribute("gen_ai.response.model", resp.model)
            span.set_attribute("gen_ai.response.finish_reasons", [resp.choices[0].finish_reason])
            span.set_attribute("gen_ai.usage.input_tokens", resp.usage.prompt_tokens)
            span.set_attribute("gen_ai.usage.output_tokens", resp.usage.completion_tokens)
            return resp
  1. The budget is injected like everything else.line 26
  2. The estimate is made from the finished prompt, so it includes the system message and the retrieved context, not just the question.line 44
  3. Recorded on the span: comparing it with gen_ai.usage.input_tokens later shows how good the estimate is.line 45
  4. The guard runs **before** _chat, so a refused request costs nothing.line 47
  5. Makes refusals easy to find in a tracing UI: search for app.refused=budget.line 49
  6. A bare raise re-throws the same exception, like throw e;. The with block then marks the span as ERROR and records the exception.line 51
  7. After the call: add the **real** input and output tokens to the user's total.line 54
ask.py 6 new or changed lines
import argparse
import sys

import openai

from app import Assistant
from budget import BudgetExceeded, TokenBudget
from config import settings
from cost import cost_usd, usd
from llm import make_client
from tracing import setup_tracing


def main() -> None:
    parser = argparse.ArgumentParser(description="Ask the handbook assistant a question.")
    parser.add_argument("question", nargs="+")
    parser.add_argument("--user", default="anonymous")
    args = parser.parse_args()

    s = settings()
    tracer_provider = setup_tracing(s.exporter)
    budget = TokenBudget(s.daily_token_budget, path="usage.json")
    bot = Assistant(make_client(), s.model, tracer_provider.get_tracer("assistant"), provider=s.provider, budget=budget)
    try:
        r = bot.ask(" ".join(args.question), user=args.user)
    except BudgetExceeded as e:
        sys.exit(f"Refused: {e}. The budget resets tomorrow.")
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try a shorter question or a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
    finally:
        tracer_provider.shutdown()

    print(r.answer)
    print(f"[request {r.request_id}] {r.input_tokens} in, {r.output_tokens} out, "
          f"cost {usd(r.cost_usd)}, {r.latency_ms:.0f} ms")
    for name in ("small-model", "frontier-model"):
        print(f"  the same call on {name}: {usd(cost_usd(name, r.input_tokens, r.output_tokens))}")
    print(f"{args.user} has used {budget.used(args.user)} of {s.daily_token_budget} tokens today")


if __name__ == "__main__":
    main()
  1. The command-line tool keeps counts in a file, so separate runs share them.line 22
  2. A clear refusal instead of a stack trace. sys.exit("...") prints to stderr and exits with code 1.line 26
  3. How much of today's budget this user has spent, after this request.line 40
Run
TRACE_EXPORTER=none uv run ask.py --user carol "How long is parental leave?"
DAILY_TOKEN_BUDGET=80 TRACE_EXPORTER=short uv run ask.py --user carol "How long is parental leave?"
You should seeyour text will differ: the model writes it
{"ts": "...", "level": "INFO", "msg": "request finished", "trace_id": "...", "request_id": "77e34e09cc85", "user": "carol", ...}
Parental leave is 16 weeks at full pay for every new parent.
[request 77e34e09cc85] 98 in, 14 out, cost $0.000000, 1190 ms
  the same call on small-model: $0.000023
  the same call on frontier-model: $0.000504
carol has used 112 of 20000 tokens today
retrieve               0.1 ms  UNSET  trace=96ac4232  app.retrieve.count=1
build_prompt           0.0 ms  UNSET  trace=96ac4232  app.prompt.estimated_tokens=54
{"ts": "...", "level": "WARNING", "msg": "request refused", "trace_id": "96ac42321347d65167cec0cb05920a85", "request_id": "c41e863ff4f7", "user": "carol", "reason": "budget"}
ask                    1.3 ms  ERROR  trace=96ac4232  app.request_id=c41e863ff4f7 app.user=carol app.refused=budget
Refused: carol has used 112 of 80 tokens today and this request needs about 54. The budget resets tomorrow.
Why this way? The second command lowers the limit to 80 for this one run, below what carol has already used, so her second question is over budget: refused in about a millisecond, with no chat span because the model was never called. Other users are not affected, and tomorrow carol starts again at 0. Open usage.json to see the counts.
Stuck on this step?
The second command answered instead of refusing
Check that both commands use the same --user carol, and that the first one printed a "has used" number above 80. If usage.json was deleted in between, the count started again at 0.
The estimate is far from gen_ai.usage.input_tokens
Expected: 4 characters per token is a rule of thumb, and chat formatting adds tokens. If you need exact counts before the call, use the tokenizer of your model (for example tiktoken for OpenAI models).
8

A load run: p50 and p95 latency

Send 20 requests, 4 at a time, and report the median and the slow tail, plus tokens and cost.

One request tells you little about speed. Real users feel the distribution: p50 (the median) is the typical request, p95 is the value 95% of requests are faster than, which is what your slowest users see. Averages hide the tail: 19 fast requests and one 30-second request average out to "fine".

percentile() uses the nearest-rank method: sort the values and take the one at position ceil(p/100 × n). Simple and easy to check by hand. (Monitoring tools compute percentiles from histograms; the idea is the same.)

load.py sends the five handbook questions in a loop, spread over four users, through a thread pool with four workers, like Executors.newFixedThreadPool(4). Threads suit this work: each one mostly waits for the HTTP reply, and Python releases its global lock (the GIL) while waiting. The budget lives in memory here, so the test does not use up anyone's real budget, and the per-request log lines are switched off.

stats.py
import math


def percentile(values: list[float], p: float) -> float:
    """Nearest-rank percentile: the smallest value with at least p% of all values at or below it."""
    if not values:
        raise ValueError("no values")
    ordered = sorted(values)
    rank = math.ceil(p / 100 * len(ordered))
    return ordered[max(rank, 1) - 1]
  1. There is no percentile of nothing: fail clearly instead of returning a made-up number.line 7
  2. The 1-based rank: for 20 values, p95 is rank 19 and p50 is rank 10.line 9
  3. Back to a 0-based index. max(rank, 1) makes p0 return the smallest value instead of index -1 (which in Python means "the last one").line 10
load.py
import argparse
import logging
import time
from concurrent.futures import ThreadPoolExecutor

from app import Assistant
from budget import BudgetExceeded, TokenBudget
from config import settings
from cost import cost_usd, usd
from llm import make_client
from stats import percentile
from tracing import setup_tracing

QUESTIONS = [
    "How many days of holiday do I get?",
    "How long is parental leave?",
    "How many days a week can I work remotely?",
    "What is the meal allowance on business trips?",
    "What do I do if I lose my laptop?",
]


def main() -> None:
    parser = argparse.ArgumentParser(description="Send many questions and report latency and cost.")
    parser.add_argument("--requests", type=int, default=20)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--exporter", default="none")
    args = parser.parse_args()

    logging.getLogger("assistant").setLevel(logging.WARNING)  # keep refusals, skip 20 "finished" lines
    s = settings()
    tracer_provider = setup_tracing(args.exporter)
    budget = TokenBudget(s.daily_token_budget)  # in memory: a load test must not use up real users' budgets
    bot = Assistant(make_client(), s.model, tracer_provider.get_tracer("load"), provider=s.provider, budget=budget)

    def one(i: int):
        try:
            return bot.ask(QUESTIONS[i % len(QUESTIONS)], user=f"user-{i % 4}")
        except BudgetExceeded:
            return None

    start = time.perf_counter()
    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        results = list(pool.map(one, range(args.requests)))
    wall = time.perf_counter() - start
    tracer_provider.shutdown()

    done = [r for r in results if r is not None]
    if not done:
        raise SystemExit("every request was refused: raise DAILY_TOKEN_BUDGET")
    latencies = [r.latency_ms for r in done]
    tokens_in = sum(r.input_tokens for r in done)
    tokens_out = sum(r.output_tokens for r in done)
    print(f"{len(done)} requests done, {len(results) - len(done)} refused, {args.workers} at a time, {wall:.1f} s in total")
    print(f"latency p50 {percentile(latencies, 50):8.0f} ms")
    print(f"latency p95 {percentile(latencies, 95):8.0f} ms")
    print(f"latency max {max(latencies):8.0f} ms")
    print(f"tokens: {tokens_in} in, {tokens_out} out; cost on {s.model}: {usd(cost_usd(s.model, tokens_in, tokens_out))}")
    per_1000 = cost_usd("small-model", tokens_in, tokens_out) / len(done) * 1000
    print(f"the same traffic on small-model: {usd(per_1000)} per 1,000 requests")


if __name__ == "__main__":
    main()
  1. argparse converts the flag to an int for you: --requests 50.line 25
  2. Raises the level for this run only: INFO lines ("request finished") are skipped, WARNING lines (refusals) still show.line 30
  3. No path: counts stay in memory and disappear when the run ends.line 33
  4. A function inside a function: it can use bot from the outer function (a closure, like a lambda capturing a variable in Java).line 36
  5. A refused request is a result too: None, counted below.line 39
  6. A pool of 4 threads. The with block waits for all tasks and shuts the pool down at the end.line 43
  7. Calls one(0), one(1), ... on the pool and returns the results in the original order. list(...) collects them.line 44
  8. Only the answered requests count for latency.line 48
  9. The slow tail. Watch the first requests: the model loading into memory shows up here, not in p50.line 56
  10. Average cost per request on the example hosted model, times 1,000: the number for a budget discussion.line 59
Run
uv run load.py --requests 20 --workers 4
You should seeyour text will differ: the model writes it
20 requests done, 0 refused, 4 at a time, 31.4 s in total
latency p50     5820 ms
latency p95     9410 ms
latency max     9930 ms
tokens: 2120 in, 372 out; cost on llama3.2:3b: $0.000000
the same traffic on small-model: $0.027060 per 1,000 requests
Why this way? Compare p50 with a single request: one question alone took about 0.4 s on an Apple-silicon Mac, but with 4 at a time each one took about 2.1 s. The model is shared, so concurrent requests wait for each other, and that is the latency users feel at busy times. Try --workers 1 and then --workers 8. More workers do not make one local model faster: Ollama runs only a few requests at once (its OLLAMA_NUM_PARALLEL setting), and those share the same CPU or GPU, so beyond that p95 grows while the total time improves little. That is the kind of fact a load run finds in a minute and a design review argues about for an hour.
Stuck on this step?
Every request is slow (10 seconds or more)
The model runs on the CPU, and four requests share it. Use --workers 1 or a smaller model (ollama pull llama3.2:1b, then LLM_MODEL=llama3.2:1b).
Some requests are refused
Each of the four users hit DAILY_TOKEN_BUDGET. Raise it for the run: DAILY_TOKEN_BUDGET=1000000 uv run load.py.
9

Test it with an in-memory exporter and a fake server

Prove the span tree, the GenAI attributes, the budget and the error handling, in milliseconds, with no model.

Tracing code is code, and it breaks quietly: a span outside its parent, an attribute name with a typo. The SDK ships an InMemorySpanExporter that keeps finished spans in a list, so a test can run a request and then inspect every span.

The model is replaced by a fake server: a Python function that receives each HTTP request and returns a response. httpx2.MockTransport plugs it into a real OpenAI client, so the real SDK builds the real request and parses the real response; only the network is fake.

Each test builds its own TracerProvider and does not make it global (set_tracer_provider can only be called once per process). The tracer goes into Assistant through the constructor, which is why the class takes it as a parameter.

test_units.py covers the small pieces: prices, percentiles, the budget (with a fake "today") and the JSON log line.

test_tracing.py
import httpx2
import openai
import pytest
from openai import OpenAI
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode

from app import Assistant
from budget import BudgetExceeded, TokenBudget

REPLY = {
    "id": "x", "object": "chat.completion", "created": 0, "model": "llama3.2:3b",
    "choices": [{"index": 0, "message": {"role": "assistant", "content": "25 days a year."}, "finish_reason": "stop"}],
    "usage": {"prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150},
}


class FakeServer:
    """A fake OpenAI-compatible server: counts calls and answers with REPLY (or an error)."""

    def __init__(self, status: int = 200):
        self.status = status
        self.calls = 0

    def __call__(self, request: httpx2.Request) -> httpx2.Response:
        self.calls += 1
        if self.status != 200:
            return httpx2.Response(self.status, json={"error": {"message": "boom"}})
        return httpx2.Response(200, json=REPLY)


@pytest.fixture
def exporter():
    return InMemorySpanExporter()


def make_assistant(exporter, server, budget=None):
    tracer_provider = TracerProvider()
    tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))
    client = OpenAI(base_url="http://fake/v1", api_key="test", max_retries=0,
                    http_client=httpx2.Client(transport=httpx2.MockTransport(server)))
    return Assistant(client, "llama3.2:3b", tracer_provider.get_tracer("test"), provider="ollama",
                     budget=budget or TokenBudget(10_000))


def by_name(exporter):
    return {s.name: s for s in exporter.get_finished_spans()}


def test_one_trace_with_three_child_spans(exporter):
    make_assistant(exporter, FakeServer()).ask("How many days of holiday do I get?", user="alice")
    spans = by_name(exporter)
    assert set(spans) == {"ask", "retrieve", "build_prompt", "chat llama3.2:3b"}
    root = spans["ask"]
    assert root.parent is None
    for name in ("retrieve", "build_prompt", "chat llama3.2:3b"):
        assert spans[name].parent.span_id == root.context.span_id
        assert spans[name].context.trace_id == root.context.trace_id


def test_model_span_follows_genai_conventions(exporter):
    make_assistant(exporter, FakeServer()).ask("How long is parental leave?")
    chat = by_name(exporter)["chat llama3.2:3b"]
    assert chat.kind == SpanKind.CLIENT
    assert chat.attributes["gen_ai.operation.name"] == "chat"
    assert chat.attributes["gen_ai.request.model"] == "llama3.2:3b"
    assert chat.attributes["gen_ai.usage.input_tokens"] == 120
    assert chat.attributes["gen_ai.usage.output_tokens"] == 30
    assert chat.attributes["gen_ai.response.finish_reasons"] == ("stop",)


def test_result_has_tokens_and_zero_cost_for_a_local_model(exporter):
    r = make_assistant(exporter, FakeServer()).ask("How long is parental leave?")
    assert (r.answer, r.input_tokens, r.output_tokens, r.cost_usd) == ("25 days a year.", 120, 30, 0.0)
    assert by_name(exporter)["ask"].attributes["app.request_id"] == r.request_id


def test_budget_refuses_without_calling_the_model(exporter):
    server = FakeServer()
    bot = make_assistant(exporter, server, TokenBudget(daily_limit=200))
    bot.ask("How long is parental leave?", user="bob")  # uses 150 of 200
    with pytest.raises(BudgetExceeded):
        bot.ask("How long is parental leave?", user="bob")
    assert server.calls == 1
    root = [s for s in exporter.get_finished_spans() if s.name == "ask"][-1]
    assert root.status.status_code == StatusCode.ERROR
    assert root.attributes["app.refused"] == "budget"
    bot.ask("How long is parental leave?", user="carol")  # other users are not affected


def test_model_error_is_recorded_on_the_span(exporter):
    with pytest.raises(openai.InternalServerError):
        make_assistant(exporter, FakeServer(status=500)).ask("How long is parental leave?")
    chat = by_name(exporter)["chat llama3.2:3b"]
    assert chat.status.status_code == StatusCode.ERROR
    assert chat.attributes["error.type"] == "InternalServerError"
    assert chat.events[0].name == "exception"
  1. The HTTP library under the openai SDK 3.x. Its MockTransport is what makes the fake server possible.line 1
  2. Part of the SDK, made for tests: get_finished_spans() returns everything exported so far.line 7
  3. A complete chat completion response, the same JSON shape Ollama and hosted APIs return. The SDK parses it into its normal objects.line 13
  4. __call__ makes an object callable like a function. The transport calls server(request); the object also counts the calls.line 27
  5. A fixture: pytest calls this and passes the result to every test with a parameter named exporter. A fresh exporter per test.line 34
  6. No SDK retries in tests: the error test fails fast instead of retrying a fake 500.line 42
  7. The real client, with the network swapped for our function.line 43
  8. a or b gives b when a is None: a generous budget unless the test passes its own.line 45
  9. The root has no parent.line 57
  10. Every other span is a direct child of ask, in the same trace.line 59
  11. The GenAI conventions checked by name, so a typo in app.py fails here.line 66
  12. The refused request never reached the server: refusals cost nothing.line 86
  13. Budgets are per user: carol is still served after bob is refused.line 90
  14. The fake answers HTTP 500, and the SDK raises openai.InternalServerError.line 95
  15. The with block recorded the exception as a span **event** (a timestamped note inside the span), with its type, message and stack trace.line 99
test_units.py
import json
import logging
from datetime import date

import pytest
from opentelemetry.sdk.trace import TracerProvider

from budget import BudgetExceeded, TokenBudget, estimate_tokens
from cost import cost_usd
from logs import JsonFormatter
from stats import percentile


def test_cost_of_a_hosted_model():
    # 1,000 in and 500 out at $0.15 and $0.60 per million
    assert cost_usd("small-model", 1000, 500) == pytest.approx(0.00045)


def test_local_model_is_free_and_unknown_model_has_no_price():
    assert cost_usd("llama3.2:3b", 10_000, 10_000) == 0.0
    assert cost_usd("model-nobody-priced", 10, 10) is None


def test_percentile_nearest_rank():
    values = [float(v) for v in range(1, 101)]  # 1.0 .. 100.0
    assert percentile(values, 50) == 50.0
    assert percentile(values, 95) == 95.0
    assert percentile([30.0, 10.0, 20.0], 50) == 20.0


def test_budget_is_per_user_per_day_and_saved(tmp_path):
    day = date(2026, 1, 5)
    path = tmp_path / "usage.json"
    budget = TokenBudget(100, path=str(path), today=lambda: day)
    budget.record("alice", 90)
    with pytest.raises(BudgetExceeded):
        budget.check("alice", 20)
    budget.check("bob", 20)  # bob has his own budget
    assert TokenBudget(100, path=str(path), today=lambda: day).used("alice") == 90  # survives a restart
    day = date(2026, 1, 6)  # the lambda reads day when it is called, so now it is "tomorrow"
    budget.check("alice", 20)


def test_estimate_tokens_is_about_four_characters_per_token():
    assert estimate_tokens([{"role": "user", "content": "x" * 400}]) == 101


def test_json_log_line_carries_the_trace_id():
    tracer = TracerProvider().get_tracer("test")
    record = logging.LogRecord("assistant", logging.INFO, __file__, 1, "request finished", None, None)
    record.fields = {"request_id": "abc123"}
    with tracer.start_as_current_span("ask") as span:
        line = JsonFormatter().format(record)
    entry = json.loads(line)
    assert entry["msg"] == "request finished"
    assert entry["request_id"] == "abc123"
    assert entry["trace_id"] == format(span.get_span_context().trace_id, "032x")
  1. Compare floats with a tolerance: 0.1 + 0.2 == 0.3 is False in every language.line 16
  2. An unknown model has no price, rather than a made-up 0.line 21
  3. 1 to 100: here the p-th percentile is simply p, easy to check by hand.line 25
  4. A pytest built-in fixture: a fresh temporary folder per test, deleted later. No usage.json left in your project.line 31
  5. A tiny function returning day. It reads the variable each time it is called, so changing day below moves "today".line 34
  6. A second TokenBudget reading the same file sees alice's 90 tokens.line 39
  7. Builds a log record by hand, the object log.info(...) would create, so the formatter can be tested directly.line 50
  8. Format the record while a span is current, then check the trace id in the JSON matches it.line 52
Run
uv run pytest -q
You should see
...........                                              [100%]
11 passed in 0.62s
Why this way? These tests check your instrumentation: span names, the tree, attribute names, the guard and the error path. Whether the model gives good answers is a different question, answered by an evals pipeline (the previous lab), not by unit tests.
Stuck on this step?
ModuleNotFoundError: No module named 'httpx2'
Run uv add --dev httpx2. (It is already installed as part of openai, but declaring it makes the dependency explicit.)
ModuleNotFoundError: No module named 'app'
Run pytest from the project folder, where app.py is, with uv run pytest -q.
10

Optional: see the waterfall in Jaeger

Send spans over OTLP to Jaeger in Docker and look at each request as a timeline in the browser.

Jaeger is an open-source tracing backend: it stores spans and shows each trace as a waterfall. Version 2 is built on the OpenTelemetry Collector and accepts OTLP, OpenTelemetry's own protocol, directly. The all-in-one image keeps traces in memory, which is perfect for local work (they disappear when the container stops).

On the app side you add the OTLP exporter package and a third branch in setup_tracing(). Over the network, spans are sent in batches by a BatchSpanProcessor on a background thread, so a slow tracing backend never slows down a request. OTLPSpanExporter() with no arguments sends to http://localhost:4318/v1/traces, or wherever the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable points.

Start Jaeger, run a few requests with TRACE_EXPORTER=otlp, then open http://localhost:16686, pick the service traced-assistant and click Find Traces. Click a trace to see ask with its three children as bars on a timeline, and click the chat bar to see the gen_ai.* attributes.

docker-compose.yml
services:
  jaeger:
    image: cr.jaegertracing.io/jaegertracing/jaeger:2.23.0
    ports:
      - "16686:16686"  # the Jaeger web UI
      - "4317:4317"    # OTLP over gRPC
      - "4318:4318"    # OTLP over HTTP (what our exporter uses)
  1. Jaeger 2, pinned to an exact version from the official registry, so the lab works the same next year.line 3
  2. The web UI: http://localhost:16686.line 5
  3. OTLP over HTTP with protobuf: what opentelemetry-exporter-otlp-proto-http sends. (4317 is the gRPC version.)line 7
tracing.py 5 new or changed lines
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor


def one_line(span: ReadableSpan) -> str:
    """A short console format: name, duration, status, the start of the trace id, attributes."""
    ms = (span.end_time - span.start_time) / 1_000_000
    status = span.status.status_code.name
    trace_id = format(span.context.trace_id, "032x")[:8]
    attrs = " ".join(f"{k}={v}" for k, v in span.attributes.items())
    return f"{span.name:<18} {ms:7.1f} ms  {status:<5}  trace={trace_id}  {attrs}\n"


def setup_tracing(exporter: str, service_name: str = "traced-assistant") -> TracerProvider:
    provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
    if exporter == "console":
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
    elif exporter == "short":
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
    elif exporter == "otlp":
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

        provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    elif exporter != "none":
        raise ValueError(f"unknown TRACE_EXPORTER {exporter!r}: use console, short, otlp or none")
    trace.set_tracer_provider(provider)
    return provider
  1. Collects spans and sends them in batches from a background thread. shutdown() in ask.py sends the last batch before the program ends.line 4
  2. Imported only in this branch, so the console modes work even without the exporter package installed.line 23
  3. Defaults to http://localhost:4318/v1/traces. Set OTEL_EXPORTER_OTLP_ENDPOINT to send elsewhere (a collector, a hosted tracing service) without changing code.line 25
Run
uv add "opentelemetry-exporter-otlp-proto-http==1.45.2"
docker compose up -d
TRACE_EXPORTER=otlp uv run ask.py --user alice "How long is parental leave?"
uv run load.py --requests 10 --exporter otlp
You should seeyour text will differ: the model writes it
 + opentelemetry-exporter-otlp-proto-http==1.45.2
 ...
 ✔ Container traced-assistant-jaeger-1  Started
{"ts": "...", "level": "INFO", "msg": "request finished", "trace_id": "79a14d0764a59b58c2ea7b7a9926a2b8", ...}
Parental leave is 16 weeks at full pay for every new parent.
[request d329b62e332b] 98 in, 14 out, cost $0.000000, 1215 ms
...
10 requests done, 0 refused, 4 at a time, 16.2 s in total
...
(then open http://localhost:16686, service traced-assistant, Find Traces)
Why this way? Copy a trace_id from a log line and paste it into Jaeger's search box: you land on exactly that request. That jump from a log line to its trace, and from a slow trace to its log line, is what makes observability useful when something goes wrong at 3 a.m.
Stuck on this step?
Transient error ... localhost, port=4318 ... Connection refused ... retrying, then Failed to export spans batch
Jaeger is not running, so the exporter retried for a few seconds and gave up. The answer still printed: tracing never breaks the request. Start Jaeger with docker compose up -d and check docker compose ps.
No traced-assistant in Jaeger's service list
Reload the page after running a request; the list only shows services that have sent spans. Also check TRACE_EXPORTER=otlp was set for that run.
Cannot connect to the Docker daemon
Start Docker Desktop (or sudo systemctl start docker on Linux) and run the command again.

Check it works

Three checks: the tests pass with no model, one request prints its four spans in the short format with the GenAI attributes and a cost, and the load run reports p50 and p95.

In the span lines, retrieve, build_prompt and chat llama3.2:3b share the trace id of ask, and ask takes about as long as chat: the model is the request.

Test
uv run pytest -q && TRACE_EXPORTER=short uv run ask.py "How long is parental leave?" && uv run load.py --requests 10
You should see
11 passed in 0.97s
retrieve               0.0 ms  UNSET  trace=9d40269f  app.retrieve.count=1
build_prompt           0.0 ms  UNSET  trace=9d40269f  app.prompt.estimated_tokens=54
chat llama3.2:3b      384.5 ms  UNSET  trace=9d40269f  gen_ai.operation.name=chat ... gen_ai.usage.input_tokens=77 gen_ai.usage.output_tokens=9
{"ts": "...", "level": "INFO", "msg": "request finished", "trace_id": "9d40269f93d0251833702e498cfce2a2", ...}
ask                  385.9 ms  UNSET  trace=9d40269f  app.request_id=383a2f90b028 app.user=anonymous app.cost_usd=0.0
Parental leave is 16 weeks.
[request 383a2f90b028] 77 in, 9 out, cost $0.000000, 385 ms
  the same call on small-model: $0.000017
  the same call on frontier-model: $0.000366
anonymous has used 86 of 20000 tokens today
10 requests done, 0 refused, 4 at a time, 5.7 s in total
latency p50     2143 ms
latency p95     2241 ms
latency max     2241 ms
tokens: 906 in, 213 out; cost on llama3.2:3b: $0.000000
the same traffic on small-model: $0.026370 per 1,000 requests

Troubleshooting

Spans from a short script never show up in Jaeger

The BatchSpanProcessor sends in the background, every few seconds. A script that ends without tracer_provider.shutdown() (or force_flush()) loses the last batch. ask.py and load.py call shutdown() in a finally or at the end for this reason.

Overriding of current TracerProvider is not allowed

trace.set_tracer_provider() was called twice in one process (for example from a test and from app code). Set it once at startup. In tests, build a TracerProvider and pass its tracer in, as test_tracing.py does.

Child spans appear as separate traces

A child was started outside its parent's with block, or in another thread. start_as_current_span uses the current context of this thread; for work you hand to a thread pool, start the span inside the task (as load.py does by calling bot.ask in the worker) or pass the context along with opentelemetry.context.

Invalid type NoneType for attribute warning

Span attributes must be strings, numbers, booleans or lists of those. Check for None before set_attribute, like app.py does for the cost.

Cost shows $0.000000 on a hosted model

The price table has the model at (0.0, 0.0) or under a different name. The name must match LLM_MODEL exactly. Unknown names print unknown, never 0.

The console is flooded with JSON spans

Use TRACE_EXPORTER=short for one line per span, or none to switch output off. Spans are still created; only the export changes.

What changes in production

  • Use the standard gen_ai.* names, and keep your own attributes under a prefix like app.. Then LLM-aware backends (Datadog, Langfuse, Arize Phoenix, Grafana) can show tokens and models without custom setup. For less hand-written code, the opentelemetry-instrumentation-openai-v2 package (beta) creates these spans for the OpenAI SDK automatically; check that it supports your SDK version. In Java, Spring AI records chat calls as Micrometer observations with gen_ai.* attribute names, which Micrometer Tracing can export over OTLP.
  • Do not put prompts and answers on spans by default. They can hold personal data and they are large. Record counts, ids and sizes; capture content only where it is allowed, sampled, and with a retention limit.
  • Send spans to a Collector, and sample. In production the app exports OTLP to an OpenTelemetry Collector, which batches, filters, removes sensitive attributes and forwards. At high traffic keep every error and slow trace but only a fraction of the normal ones (tail sampling in the Collector).
  • Keep budgets in a shared store. A file works for one process. With several servers, count in Redis (INCRBY on a key like tokens:2026-11-29:alice, with a 2-day expiry) or your database, reserve tokens for the expected output as well as the prompt, and alert on users near their limit.
  • Alert on p95 and on cost per request, not on averages. Track both per model and per feature. A prompt change that adds 500 tokens shows up as cost per request the same day, long before the monthly invoice.

Interview angle

“How would you make an LLM feature observable and keep its cost under control?”

I trace every request with OpenTelemetry: a root span per request with child spans for retrieval, prompt building, each model call and each tool call. The model spans follow the GenAI semantic conventions, so they carry the operation, the provider, the requested and returned model, finish reasons and input and output tokens, and any backend can read them. I export over OTLP to a Collector that samples and strips sensitive data. From the token counts I compute cost per request from a price table, attached to the span and to a structured JSON log line with the request id and trace id, so support tickets, logs and traces link up. I watch p50 and p95 latency rather than averages, and cost per request per feature. To cap spend, a per-user daily token budget checks an estimate before the model call and records the real usage after it, in a shared store like Redis. The instrumentation itself is unit tested with an in-memory span exporter and a fake model server.

Clean up

Stop Jaeger if you started it (its traces are in memory and go with it). usage.json holds today's token counts; delete it to reset every user's budget. Keep the project: the last lab ships this app in Docker.

Run
docker compose down
rm -f usage.json

Practice

No model needed: these run in your browser and check your answer.

p50 and p95 by nearest rank

Write percentile(values, p) with the nearest-rank method: sort the values, take the one at 1-based rank ceil(p / 100 * n), and treat a rank below 1 as 1. Raise ValueError for an empty list. The starter returns the average, which is a different thing.

Exercise
import math


def percentile(values, p):
    return sum(values) / len(values)


latencies = [120, 80, 95, 3000, 110, 90, 100, 105, 85, 130]
print(percentile(latencies, 50), percentile(latencies, 95))
Hint

Sort with `sorted(values)`, compute `rank = math.ceil(p / 100 * len(ordered))`, and return `ordered[max(rank, 1) - 1]`.

Who went over budget? Read the JSON logs

You get the app's log lines as strings (one JSON object each). Write over_budget(lines, limit): add up input_tokens + output_tokens per user, using only lines whose msg is "request finished", and return the sorted list of users whose total is above limit.

Exercise
import json


def over_budget(lines, limit):
    users = []
    # your code here
    return users


logs = [
    '{"msg": "request finished", "user": "alice", "input_tokens": 100, "output_tokens": 20}',
    '{"msg": "request finished", "user": "bob", "input_tokens": 40, "output_tokens": 10}',
    '{"msg": "request refused", "user": "alice", "reason": "budget"}',
    '{"msg": "request finished", "user": "alice", "input_tokens": 90, "output_tokens": 30}',
]
print(over_budget(logs, 200))
Hint

Parse each line with `json.loads`, skip it unless `entry["msg"] == "request finished"`, keep a dict of totals with `totals[user] = totals.get(user, 0) + ...`, then `sorted(u for u, t in totals.items() if t > limit)`.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip)