Skip to content
Visual explainer 2h to learn 4 steps

Tracing, logging & feedback

Trace every model call with inputs, outputs, latency and cost and collect user feedback.

By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.

Topic 27 of 33

In short

Tracing records every step of a request, such as retrieval, model calls and tool calls, with inputs, outputs, latency and cost. Combined with user feedback, traces show where and why the app fails in production.

Explained simply

In production you cannot watch over every user's shoulder. Tracing records the journey of each request: the rewritten query, the chunks found, each model call, each tool call. For every step it notes what went in, what came out, how long it took and what it cost.

A trace is the record of one whole request. A span is one timed step inside it, and spans can contain smaller spans, like folders inside folders. A slow answer becomes easy to explain: you can see that 1.9 of its 2.4 seconds went to one model call.

Logs show what happened. Feedback shows whether users were happy. A simple thumbs up or down, linked to the trace ID, tells you which traces to read first.

The real value comes from a habit: every week, read failing and down-voted traces, find patterns, fix the biggest one, and add those cases to your eval set. That loop is how an LLM app gets better after launch.

Press Play on a diagram to walk through it one step at a time.

MapOne request trace
Trace: POST /chat (2.4 s)
  • Span: rewrite query
    • model call, 0.3 s
    • 180 tokens
  • Span: retrieve
    • vector search, 0.1 s
    • 5 chunks
  • Span: generate
    • model call, 1.9 s
    • 2,100 tokens
    • prompt v3
  • User feedback
    • thumbs down
    • wrong refund policy
SequenceHow a thumbs down finds its trace
User
API
LLM
Trace store
  1. 1Question
    User to API: Question
  2. 2Model call
    API to LLM: Model call
  3. 3Reply plus token usage
    LLM to API: Reply plus token usage
  4. 4Spans with trace_id
    API to Trace store: Spans with trace_id
  5. 5Answer plus trace_id
    API to User: Answer plus trace_id
  6. 6Thumbs down, trace_id, reason
    User to API: Thumbs down, trace_id, reason
  7. 7Attach feedback to trace
    API to Trace store: Attach feedback to trace

In depth

What to record on every model call

A model call span should answer: which model, with which prompt, cost how much, took how long, and how did it end? Record the model name and exact version, the prompt template version, and key parameters such as temperature and the maximum output tokens. Record token usage from the API response: input tokens, output tokens, and cached input tokens if your provider reports them. Compute cost from usage and a price table you keep in config.

Record latency two ways: total time and, for streaming, time to first token, which is what users feel. Record the stop or finish reason; a reason meaning the output hit the length limit tells you the answer was cut off. Record retries and errors.

Whether to store full inputs and outputs depends on privacy rules. They are the most useful debugging data, so store them redacted if you can, with limited access and a short retention period.

  • Model and version, prompt version, parameters
  • Input, output and cached tokens, plus cost
  • Total latency and time to first token
  • Finish reason, retries and errors
  • Redacted input and output, if policy allows

OpenTelemetry and the GenAI conventions

OpenTelemetry (OTel) is the vendor-neutral standard for traces, metrics and logs. Its Python SDK creates spans, and an exporter sends them, usually over the OTLP protocol, to whatever backend you choose: general tools like Jaeger or Grafana Tempo, or LLM-focused tools such as Langfuse or Arize Phoenix. Because the format is standard, you can switch backends without touching your code.

OTel defines semantic conventions for generative AI, so tools agree on attribute names, for example gen_ai.request.model, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. These conventions are still evolving, so check the current specification before relying on exact names.

Traces also cross service boundaries. When your API calls a separate retrieval service, the trace context travels in the traceparent HTTP header, and both services' spans join the same trace.

LayersHow a span reaches your dashboard
  1. 1
    Your code

    Creates spans and sets attributes

  2. 2
    OTel SDK

    Batches finished spans

  3. 3
    OTLP exporter

    Sends them over the network

  4. 4
    Collector (optional)

    Filters, samples, redacts, routes

  5. 5
    Backend

    Search, timelines, dashboards

Cost and latency from traces

Once every model span carries tokens and cost, you can answer questions that otherwise need guesswork. Which feature costs the most? Which prompt version doubled the output length? Which ten users produce 40% of the spend? Group cost by feature, user, prompt version and model.

For latency, use percentiles, not averages. If p50 is 1.2 seconds but p95 is 9 seconds, one user in twenty waits a long time, and the average hides it. Look at the slow traces: often the cause is one huge input, a retry after a timeout, or an agent that took eight steps.

For streaming apps, chart time to first token separately. Users tolerate a long answer that starts quickly much better than a short one that starts late.

Feedback that is actually useful

Explicit feedback is a thumbs up or down, ideally with a few reason buttons such as wrong, not helpful, unsafe, too long, plus an optional comment. Always send the trace ID with it, so every vote points to the exact request, prompt version and retrieved chunks.

Most users never click anything, so collect implicit signals too: the user copied the answer (good sign), pressed regenerate, asked the same question again in different words, abandoned the chat, or asked for a human (bad signs). These are noisier but far more plentiful.

Feedback is a pointer, not a score. A thumbs down may mean the answer was wrong, or simply that the policy is unpopular. Read the trace, decide what really went wrong, and turn real failures into eval cases with the correct expected behaviour.

CycleThe improvement loop
  1. 1
    Trace every request

    Spans, tokens, cost, latency

  2. 2
    Collect feedback

    Votes and implicit signals

  3. 3
    Review bad traces

    Group failures by cause

  4. 4
    Add eval cases

    With the correct expected behaviour

  5. 5
    Fix and ship

    Gated by evals in CI

  6. Back to step 1

Privacy, retention and sampling

Traces of LLM apps contain what users typed, which may include names, health details or passwords pasted by mistake. Redact before storage: replace emails, phone and card numbers with placeholders, and store a pseudonymous user ID instead of a real name. Decide a retention period, such as 30 days for full content and longer for metrics only, and restrict who can read raw traces.

At high volume, storing every trace gets expensive. Sampling keeps a share. Head sampling decides at the start of a request, which is cheap but random. Tail sampling decides after the request finishes, so you can keep every trace with an error, high latency or negative feedback, and only a small percentage of normal ones. The OpenTelemetry Collector supports tail sampling.

Never sample away the traces that explain your failures.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Trace every model call~30m
  2. 2
    Log inputs, outputs, latency and cost~30m
  3. 3
    Collect user feedback~30m
  4. 4
    Review traces to find failures~30m

Key points

  • Give each request a trace ID and record every step as a span.
  • Log prompt version, model, tokens, cost and latency for each model call.
  • Collect simple feedback like thumbs up or down and link it to the trace.
  • Redact personal data before storing logs.
  • Turn failing traces into new eval cases.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import time, uuid, json
from contextlib import contextmanager

@contextmanager
def span(trace_id: str, name: str, **attrs):
    start = time.perf_counter()
    try:
        yield attrs
    finally:
        attrs['ms'] = round((time.perf_counter() - start) * 1000)
        print(json.dumps({'trace': trace_id, 'span': name, **attrs}))

trace_id = str(uuid.uuid4())
with span(trace_id, 'generate', model='small-model', prompt_version='v3') as s:
    s['tokens_out'] = 120  # set from the API's usage data

A minimal span logger with timing and attributes.

Nested spans with OpenTelemetry

You want each chat request to show up as one trace with a retrieve span and a generate span. Step 1: get a tracer. Step 2: open a root span for the request and tag the prompt version. Step 3: open child spans for retrieval and generation; spans opened inside another become its children automatically. Step 4: set GenAI attributes from the API's usage data. Note: without configuring a TracerProvider and an exporter at startup, the API calls do nothing, which is safe for tests but shows no data.

python
from opentelemetry import trace

tracer = trace.get_tracer("rag-app")

def answer(question: str) -> str:
    with tracer.start_as_current_span("chat") as root:
        root.set_attribute("app.prompt_version", "v3")
        with tracer.start_as_current_span("retrieve") as s:
            chunks = search(question)
            s.set_attribute("app.chunks", len(chunks))
        with tracer.start_as_current_span("generate") as s:
            reply = call_model(question, chunks)
            s.set_attribute("gen_ai.usage.input_tokens", reply.input_tokens)
            s.set_attribute("gen_ai.usage.output_tokens", reply.output_tokens)
        return reply.text

A weekly trace review that found two problems

Last week the app handled 4,200 requests, and 38 got a thumbs down. Step 1: filter traces with negative feedback and read 20 of them, noting a cause for each. Step 2: the causes group up: 9 retrieved an old pricing page, 6 answers were too long, 3 called the wrong tool, 2 were users unhappy with a correct policy answer. Step 3: the biggest bucket is retrieval of stale pages. The ingestion job had skipped a folder; fix it and re-index. Step 4: a cost view shows one API key producing 30% of spend by sending 50-page documents. Add an input size limit. Step 5: add the 9 pricing questions and 3 tool cases to the eval set, so CI guards both fixes.

Quick reference

  • Trace = one request; span = one timed step; spans nest
  • Log model, prompt version, tokens, cost, latency, time to first token and finish reason
  • OTel GenAI attributes: gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens
  • Return the trace ID to the client so feedback can be attached to it
  • Use p50 and p95 latency, not averages
  • Redact personal data before storing traces; set a retention period
  • Tail sampling keeps all errors, slow requests and down-voted traces
  • Every reviewed failure becomes an eval case

Common mistakes

  • Logging full prompts with personal data and no redaction.
  • Collecting feedback without linking it to the trace that produced it.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the relationship between a trace and a span?

Question 2

2p50 latency is 1.2 s and p95 is 9 s. What does that tell you?

Question 3

3Why should the API return the trace ID with each answer?

Question 4

4A model span's finish reason shows the output hit the length limit. What happened?

Question 5

5Why use tail sampling instead of keeping a random 5% of traces?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a function that computes the cost of a model call from input and output token counts and per-million-token prices.

  2. Exercise 2medium

    Write a redaction function for traces that replaces emails, card-like numbers (13 to 19 digits, spaces or dashes allowed) and phone-like numbers with placeholders.

  3. Exercise 3hard

    Given a list of span dicts (trace_id, name, ms, cost, feedback), print p50 and p95 latency of generate spans, total cost per trace, and the IDs of traces with negative feedback sorted by cost.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is LLM observability?
Being able to see what your LLM app did on each request: inputs, outputs, retrieved context, tool calls, tokens, cost and latency, plus user feedback, so you can find and fix failures.
Do I need a special tool to trace LLM calls?
No. OpenTelemetry works with any backend, and even structured JSON logs with a trace ID are a good start. LLM-focused tools add nicer views for prompts and evals.
Is it safe to log prompts and responses?
Only with care. Redact personal data, restrict access, set a retention period, and follow your privacy policy and local law.
What is time to first token?
The delay between sending a request and receiving the first streamed token. It is the latency users feel most in chat apps.
ShareXLinkedInWhatsApp