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
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
- Lab 1 done: Your first LLM call. This lab reuses its
.env,config.pyand cost idea. - The idea behind it (8 minutes each): Tracing and observability and Cost and latency.
- Helpful, not required: RAG from scratch. The retrieval here is a tiny word-overlap search, so you can focus on tracing.
- Python you will meet:
withblocks (Errors, retries and context managers),logging(Project structure and logging) and a thread pool (Performance: threads, processes and async). Each is explained where it appears.
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.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 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.
uv --version 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.
ollama --version
ollama pull llama3.2:3b ollama version is 0.x.y pulling manifest ... success
S4Check the model answers
ollama run llama3.2:3b "Say hello in five words." 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.
docker compose version Docker Compose version v2.x.y
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.
# 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 - Ollama's OpenAI-compatible API. A hosted provider needs only these first lines changed.line 2
- Goes into the
gen_ai.provider.namespan attribute (step 4). Useopenai,anthropicand so on for hosted APIs.line 5 - Picks where finished spans go.
consoleprints them; the others arrive in steps 4 and 10.line 8 - The per-user limit for the budget guard in step 7.line 11
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")),
) load_dotenv()copies.envintoos.environ. Real environment variables win, soTRACE_EXPORTER=short uv run ...on the command line overrides the file.line 6- A read-only settings object, like a Java record.line 9
- Environment variables are always strings;
int(...)turns the budget into a number.line 26
.venv/
__pycache__/
.env
usage.json - Never commit
.env: one day it holds a real key.line 3 - The token budget file from step 7: runtime data, not code.line 4
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) - A function that builds the client. Tests never call it: they build their own client pointed at a fake server.line 6
- The SDK retries timeouts, 429 and 5xx twice. With tracing on, each attempt is still inside one
chatspan.line 8
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 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 ...
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.
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.
# 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."},
] - A list of dicts, like a
List<Map<String, String>>. Five handbook facts the model may answer from.line 2
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}"},
] - A set of common words to ignore, so "how" and "the" do not count as matches.line 3
- Lower-case words without punctuation, minus the stop words.
{... for w in ...}is a set comprehension;-on sets is "remove these", likeremoveAll.line 7 q & words(...)is the set intersection (shared words). Sort by how many are shared, most first.key=lambda d: ...is like aComparator.comparing(d -> ...).line 14- The top
k, but only entries that share at least one word (an empty set counts as false).line 15 "\n".join(...)puts one entry per line.or "(nothing found)"gives the model something honest to read when nothing matched.line 19
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) - The result of one request: what the caller prints now and what the tests check later.line 8
- Dependencies come in through the constructor.
self.client = clientisthis.client = client.line 18 uuid4().hexis 32 random hex characters;[:12]keeps the first 12, short enough to read and unique enough for a lab.line 23perf_counter()is a high-resolution clock for measuring durations, likeSystem.nanoTime(). Never use wall-clock time for latency.line 24- The same SDK call as lab 1, now with the retrieved context in
messages.line 27 - End minus start is seconds as a float; times 1000 gives milliseconds.line 29
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() argparseis Python's built-in command-line parser (like picocli in Java or yargs in Node). It also generates--help.line 12- One or more words:
uv run ask.py How long is leaveworks without quotes, the words are joined on the next lines.line 13 - An optional flag with a default. Read it as
args.user.line 14 - Timeout first: it is a subclass of
APIConnectionError, and Python uses the firstexceptthat matches.line 21 - True only when you run this file directly (
uv run ask.py), not when another file imports it. It is Python'spublic static void main.line 30
uv run ask.py "How many days of holiday do I get?" Employees get 25 days of paid holiday a year, and unused days expire on 31 March. [request 3f9c2a7d41b0] 112 in, 21 out, 1840 ms
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.
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.
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 traceis the API package: what your code and libraries call. Thesdkimports below are the engine.line 1service.namenames your app in every trace.Resource.createalso adds SDK facts like the language and SDK version.line 8SimpleSpanProcessorexports 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 10nonemeans "make spans, send them nowhere": useful for the load run. Any other word is a typo, so fail loudly.line 11- Makes this provider the global one, so libraries that use the OpenTelemetry API find it. Call it once, at startup.line 13
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) - The tracer is injected like the client. The tests in step 9 pass a tracer that writes to memory.line 18
- The root span: everything about this request happens inside it.
as spangives you the span object to add attributes to.line 26 - Attributes are searchable key-value facts. Your own attributes get a prefix like
app.so they never clash with standard names.line 27 - A child span: it starts inside the
askblock, so its parent isask.as sbecausespanis already taken.line 29 - 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
- 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
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() - Set up tracing once, before anything makes a span.line 19
- A tracer named after the code that uses it (the "instrumentation scope"), like a logger name.line 20
finallyruns on success, on an exception and onsys.exit().shutdown()flushes spans that are still waiting, so none are lost when the program ends.line 27
uv run ask.py "How long is parental leave?" {
"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 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 asopentelemetry-api. Overriding of current TracerProvider is not allowed- Something called
setup_tracing()twice in one process. Call it once at startup; tests build their ownTracerProviderwithout making it global. - No spans are printed
- Check
TRACE_EXPORTER=consolein.envand that the shell does not override it (echo $TRACE_EXPORTER).
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.
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 SpanKindsays what role a span plays: INTERNAL (the default), CLIENT (calls out), SERVER (handles a request), and others.line 5- Who serves the model:
ollamahere. It goes on the span, not into the API call.line 20 - The model call moves into its own method, which owns its span.line 37
- The conventional span name: operation, a space, the model. Searching for
chat llama3.2:3bin a UI finds every call to that model.line 44 - CLIENT, because the model runs in another process (Ollama) or another company.line 44
chatfor chat completions. Other values includeembeddings,execute_toolandinvoke_agent.line 45- Catch, label, re-raise. The
withblock already records the exception and sets the status to ERROR;error.typeadds the short class name that dashboards group by.line 51 - The class name of the exception, like
e.getClass().getSimpleName(), for exampleAPIConnectionError.line 52 - 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
- A list, because one request can ask for several answers.
stopis normal;lengthmeans the answer was cut off.line 55 - The token counts from
usage: your bill.prompt_tokensin the SDK isinput_tokensin the conventions.line 56
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 - A formatter: a function from a finished span to text.
ConsoleSpanExportercalls it for each span.line 7 - Span times are integers in nanoseconds since 1970. Dividing the difference by a million gives milliseconds.line 9
UNSET,OKorERROR..namegives the enum constant's name, likeEnum.name()in Java.line 10- 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 :<18pads to 18 characters, left-aligned, so the columns line up.line 13- Pass the function itself (no parentheses), like a method reference
Tracing::oneLine.line 21
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() - Passed by name: easier to read than a fourth positional argument.line 20
TRACE_EXPORTER=short uv run ask.py "How long is parental leave?" 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 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?", andRemove-Item Env:TRACE_EXPORTERafterwards. 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.
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.
# 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}" - A dict from model name to a tuple
(input price, output price). A tuple is a fixed-size, read-only list.line 3 - 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
- The return type is "a float or None", like
Optional<Double>. The|syntax for types is Python 3.10+.line 11 - Tuple unpacking: two variables from a two-item tuple in one line.line 16
- Prices are per million tokens. Underscores in numbers are only for readability.line 17
- Formats the amount with six decimals, because one local-sized call costs fractions of a cent on hosted models.line 20
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 - The result now carries the cost (or None if the model has no price).line 17
- Priced by the model you **asked for**: a dated name in
resp.modelwould not be in the table.line 41 - Span attributes cannot be None, so set it only when there is a price.
is not Noneis the safe test:if cost:would also skip a real 0.0.line 42
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() - Two f-strings next to each other inside
print(...)join into one line.line 33 - The same tokens priced on the example hosted models: what this request would cost if you moved off the laptop.line 34
TRACE_EXPORTER=none uv run ask.py "How many days a week can I work remotely?" 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
Stuck on this step?
- It says
cost unknown (add the model to PRICES) - That is the guard working: your
LLM_MODELis not inPRICES. Add a row with its prices (or(0.0, 0.0)for another local model).
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).
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 - Subclass the standard formatter and override
format(), the one method that turns a record into text.line 9 - 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
- The message with any
%sarguments filled in.line 16 - The span that is current right now (the innermost open
withblock). Outside any span you get a placeholder whose context is not valid.line 18 - The same 32-hex-digit form Jaeger shows, so you can paste it into Jaeger's search box.line 20
- The
fieldsattribute if the caller passed one, otherwise an empty dict. LikeOptional.ofNullable(x).orElse(Map.of()).line 21 - Add the handler only once, even if
get_logger()is called many times (every handler would print each line again).line 27 - Do not also pass records up to the root logger, which might print them a second time in another format.line 32
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 - One logger for the module, created at import time, like a
private static final Logger.line 11 - Logged **inside** the
askspan, 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 - One decimal is plenty for milliseconds and keeps the log line short.line 51
TRACE_EXPORTER=none uv run ask.py --user alice "How many days of holiday do I get?" {"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 Stuck on this step?
- The log line has no
trace_id - The
log.info(...)call is outside thewith ... ("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. Keeplogger.propagate = Falseinget_logger().
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.
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)) - A custom exception carrying the numbers, so the caller can show a helpful message.line 7
- Several assignments in one line: each name on the left gets the value in the same position on the right.line 10
//is integer division (/in Java on ints).+ 1so even an empty prompt counts as at least one token.line 15- 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 - A mutex, like
ReentrantLockwithout the reentrant part.with self._lock:acquires it and always releases it.line 25 - Load yesterday's and today's counts from the file, if it exists.line 28
- One key per day and user, such as
2026-11-29:alice. A new day means a new key starting at 0.line 31 - Refuse if this request **could** cross the limit. Checking only
used >= limitwould let one huge request go far over.line 40 .get(key, 0)isgetOrDefault(key, 0).line 46- Save after every request. Fine for one process; several servers need a shared store (see In production).line 48
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 - The budget is injected like everything else.line 26
- The estimate is made from the finished prompt, so it includes the system message and the retrieved context, not just the question.line 44
- Recorded on the span: comparing it with
gen_ai.usage.input_tokenslater shows how good the estimate is.line 45 - The guard runs **before**
_chat, so a refused request costs nothing.line 47 - Makes refusals easy to find in a tracing UI: search for
app.refused=budget.line 49 - A bare
raisere-throws the same exception, likethrow e;. Thewithblock then marks the span as ERROR and records the exception.line 51 - After the call: add the **real** input and output tokens to the user's total.line 54
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() - The command-line tool keeps counts in a file, so separate runs share them.line 22
- A clear refusal instead of a stack trace.
sys.exit("...")prints to stderr and exits with code 1.line 26 - How much of today's budget this user has spent, after this request.line 40
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?" {"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. 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. Ifusage.jsonwas 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
tiktokenfor OpenAI models).
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.
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] - There is no percentile of nothing: fail clearly instead of returning a made-up number.line 7
- The 1-based rank: for 20 values, p95 is rank 19 and p50 is rank 10.line 9
- 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
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() argparseconverts the flag to an int for you:--requests 50.line 25- Raises the level for this run only: INFO lines ("request finished") are skipped, WARNING lines (refusals) still show.line 30
- No
path: counts stay in memory and disappear when the run ends.line 33 - A function inside a function: it can use
botfrom the outer function (a closure, like a lambda capturing a variable in Java).line 36 - A refused request is a result too:
None, counted below.line 39 - A pool of 4 threads. The
withblock waits for all tasks and shuts the pool down at the end.line 43 - Calls
one(0),one(1), ... on the pool and returns the results in the original order.list(...)collects them.line 44 - Only the answered requests count for latency.line 48
- The slow tail. Watch the first requests: the model loading into memory shows up here, not in p50.line 56
- Average cost per request on the example hosted model, times 1,000: the number for a budget discussion.line 59
uv run load.py --requests 20 --workers 4 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
--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 1or a smaller model (ollama pull llama3.2:1b, thenLLM_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.
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.
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" - The HTTP library under the openai SDK 3.x. Its
MockTransportis what makes the fake server possible.line 1 - Part of the SDK, made for tests:
get_finished_spans()returns everything exported so far.line 7 - A complete chat completion response, the same JSON shape Ollama and hosted APIs return. The SDK parses it into its normal objects.line 13
__call__makes an object callable like a function. The transport callsserver(request); the object also counts the calls.line 27- A fixture: pytest calls this and passes the result to every test with a parameter named
exporter. A fresh exporter per test.line 34 - No SDK retries in tests: the error test fails fast instead of retrying a fake 500.line 42
- The real client, with the network swapped for our function.line 43
a or bgivesbwhenais None: a generous budget unless the test passes its own.line 45- The root has no parent.line 57
- Every other span is a direct child of
ask, in the same trace.line 59 - The GenAI conventions checked by name, so a typo in
app.pyfails here.line 66 - The refused request never reached the server: refusals cost nothing.line 86
- Budgets are per user: carol is still served after bob is refused.line 90
- The fake answers HTTP 500, and the SDK raises
openai.InternalServerError.line 95 - The
withblock recorded the exception as a span **event** (a timestamped note inside the span), with its type, message and stack trace.line 99
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") - Compare floats with a tolerance:
0.1 + 0.2 == 0.3is False in every language.line 16 - An unknown model has no price, rather than a made-up 0.line 21
- 1 to 100: here the p-th percentile is simply p, easy to check by hand.line 25
- A pytest built-in fixture: a fresh temporary folder per test, deleted later. No
usage.jsonleft in your project.line 31 - A tiny function returning
day. It reads the variable each time it is called, so changingdaybelow moves "today".line 34 - A second
TokenBudgetreading the same file sees alice's 90 tokens.line 39 - Builds a log record by hand, the object
log.info(...)would create, so the formatter can be tested directly.line 50 - Format the record while a span is current, then check the trace id in the JSON matches it.line 52
uv run pytest -q ........... [100%] 11 passed in 0.62s
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.pyis, withuv run pytest -q.
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.
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) - Jaeger 2, pinned to an exact version from the official registry, so the lab works the same next year.line 3
- The web UI: http://localhost:16686.line 5
- OTLP over HTTP with protobuf: what
opentelemetry-exporter-otlp-proto-httpsends. (4317 is the gRPC version.)line 7
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 - Collects spans and sends them in batches from a background thread.
shutdown()inask.pysends the last batch before the program ends.line 4 - Imported only in this branch, so the console modes work even without the exporter package installed.line 23
- Defaults to
http://localhost:4318/v1/traces. SetOTEL_EXPORTER_OTLP_ENDPOINTto send elsewhere (a collector, a hosted tracing service) without changing code.line 25
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 + 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) 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, thenFailed 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 -dand checkdocker compose ps. - No
traced-assistantin Jaeger's service list - Reload the page after running a request; the list only shows services that have sent spans. Also check
TRACE_EXPORTER=otlpwas set for that run. Cannot connect to the Docker daemon- Start Docker Desktop (or
sudo systemctl start dockeron 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.
uv run pytest -q && TRACE_EXPORTER=short uv run ask.py "How long is parental leave?" && uv run load.py --requests 10 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 likeapp.. Then LLM-aware backends (Datadog, Langfuse, Arize Phoenix, Grafana) can show tokens and models without custom setup. For less hand-written code, theopentelemetry-instrumentation-openai-v2package (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 withgen_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 (
INCRBYon a key liketokens: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.
docker compose down
rm -f usage.jsondocker compose down
rm -f usage.jsondocker compose down
Remove-Item usage.json -ErrorAction SilentlyContinue 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.
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.
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.