Skip to content
Visual explainer 3h 30m to learn 5 steps

Trace retrieval, model and tool spans without leaking content

Correlate retrieval, model and tool spans and track p50/p95 latency, abstention, failures and spend without logging sensitive content.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 10 minutes to read.

Topic 29 of 34

In short

A trace follows one request through the assistant as a tree of spans: the API request, retrieval, each model call and each tool call, all sharing one trace ID. From those spans you derive the numbers that matter in production: p50 and p95 latency, abstention rate, failure modes and spend per request. The hard part is doing this without copying questions, passages or answers into logs, so traces record IDs, counts and timings instead of content.

Think of it like this: A trace is a parcel tracking page: it shows every depot and timestamp, not what is inside the box.

Explained simply

Once the assistant is live, people will say it feels slow, or it said it did not know, or it got something wrong. To find out why, you need a record of what happened inside each request. That record is a trace. It is made of spans, and each span is one timed step: searching, calling the model, calling a tool.

All the spans of one request share a trace ID, so you can line them up and see that the search took 80 milliseconds but the model took 3 seconds. Give the same ID back to the user as a request ID. When they report a problem, you can find the exact trace.

From many traces you get the health numbers. Latency at p50 (the typical request) and p95 (the slow ones). How often the assistant abstains. Which failures happen: timeouts, denied tools, invalid output. And how much each request costs in model tokens.

There is one big rule. Traces must not become a copy of everything people asked and every document they saw. Questions can contain personal data, and passages can be confidential. So spans store IDs, counts and timings, not the text itself.

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

MapSpans in one request
POST /ask (trace root)
  • retrieval
    • top_k, scope filter
    • returned source IDs and count
    • duration
  • chat (model ID)
    • input and output tokens
    • finish reason
    • duration
  • execute_tool ticket_status
    • status: ok, timeout or denied
    • duration
  • result
    • outcome: answer, abstain or deny
    • estimated cost
SequenceOne request and its spans
Client
API
Retriever
Model
  1. 1POST /ask (request ID r-81f2)
    Client to API: POST /ask (request ID r-81f2)
  2. 2retrieval span: top_k 8, scope staff
    API to Retriever: retrieval span: top_k 8, scope staff
  3. 35 source IDs, 70 ms
    Retriever to API: 5 source IDs, 70 ms
  4. 4chat span: 1,900 input tokens
    API to Model: chat span: 1,900 input tokens
  5. 5210 output tokens, 1.8 s
    Model to API: 210 output tokens, 1.8 s
  6. 6answer, citations, request ID
    API to Client: answer, citations, request ID

In depth

Span names and attributes from the GenAI conventions

OpenTelemetry publishes semantic conventions for generative AI, now maintained in their own repository and still marked Development, so names may change. They suggest naming an inference span as the operation and model, such as chat followed by the model ID, a tool span as execute_tool followed by the tool name, and a retrieval span as retrieval. Useful attributes include gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.tool.name and gen_ai.retrieval.top_k.

Using shared names lets tracing tools recognise your spans. Add your own attributes under an app prefix for things the conventions do not cover, such as returned source IDs, caller scope names, outcome and prompt version. Pin the conventions version you followed in your docs.

  • chat plus the model ID for model calls
  • execute_tool plus the tool name for tools
  • retrieval for search steps
  • app.* for your own attributes

Keeping sensitive content out

In the GenAI conventions, attributes that carry content, such as gen_ai.input.messages, gen_ai.output.messages, gen_ai.tool.call.arguments, gen_ai.tool.call.result and gen_ai.retrieval.query.text, are opt-in. Keep them off in production. Record what you need to debug without the text: source IDs, hit counts, scores rounded to two decimals, token counts, finish reasons and the prompt version.

Add a second safety net in the pipeline. Many OpenTelemetry Collector setups use processors that delete or hash attributes before export. Hash user IDs with a secret salt so you can count unique users without storing who they are. Write a test that runs a fixture request containing a fake email address and asserts it appears in no exported span.

CompareRecord this, not that
Record
  • Source IDs and hit count
  • Token counts and model ID
  • Outcome and failure code
  • Hashed user ID
Do not record
  • Question text
  • Retrieved passages
  • Answer text
  • Raw email or name

Latency percentiles and failure modes

Averages hide pain. If 90 requests take 1 second and 10 take 12 seconds, the mean is 2.1 seconds, which describes nobody. Percentiles are better: p50 is the median, p95 is the time 95 percent of requests beat. Compute them per route and per version, and break total time into retrieval, model and tool shares using span durations.

Give every non-answer a code from a short fixed list: abstain_no_evidence, deny_scope, clarify, tool_timeout, model_unavailable, invalid_output, budget_exhausted, client_cancelled. Counting codes per hour shows drift. A jump in abstain_no_evidence after a release often means the index or filters broke, even with zero errors.

  • p50, p95 per route and version
  • Split time by retrieval, model and tool spans
  • Fixed list of outcome and failure codes
  • Alert on rate changes, not just errors

Spend per request

Cost comes from model spans: input tokens times input price plus output tokens times output price, summed across every model call in the trace. Agents make several calls, so cost per request varies more than for fixed RAG. Keep a price table per model ID in versioned config, record the estimated cost on the root span and aggregate daily totals and p95 cost per request.

Set a budget per request in the agent and a daily budget with an alert. When cost per request rises without a change in traffic, look for longer prompts, more tool loops or a model change. With the fixture model, costs are illustrative; say so on dashboards built from local runs.

Learn it in 5 short steps

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

  1. 1
    Create spans for each step~40m
  2. 2
    Track p50 and p95 latency~40m
  3. 3
    Count abstentions and failure modes~40m
  4. 4
    Track spend per request~40m
  5. 5
    Redact sensitive content~40m

Key points

  • One trace ID per request ties retrieval, model and tool spans together; return the request ID to the caller.
  • The OpenTelemetry GenAI conventions name spans as chat plus the model ID, execute_tool plus the tool name, and retrieval; they are still marked Development.
  • Message content, tool arguments and retrieved documents are opt-in attributes in those conventions; leave them off by default.
  • Track p50 and p95 latency, not averages: the slow tail is what users complain about.
  • Count outcomes (answer, abstain, deny, error) and cost per request so you notice drift, not just outages.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from opentelemetry import trace
tracer = trace.get_tracer("kb-assistant")

def retrieve(query, caller):
    with tracer.start_as_current_span("retrieval") as span:
        span.set_attribute("gen_ai.operation.name", "retrieval")
        span.set_attribute("gen_ai.retrieval.top_k", 8)
        hits = search(query, scopes=caller.scopes)
        span.set_attribute("app.source_ids", [h.id for h in hits])
        span.set_attribute("app.hit_count", len(hits))
        return hits  # the query text itself is never recorded

Record IDs and counts on the span; leave the query and passages out.

Finding a slow tail

Users report the assistant is sometimes very slow. Step 1: compare p50 and p95: 1.4 s and 9.8 s. Step 2: filter traces above p95 and group spans by name. Step 3: execute_tool ticket_status takes 8 seconds in most of them and ends with status timeout. Step 4: the tool has no deadline shorter than the request deadline. Fix: give the tool a 2-second timeout and return a partial answer with a ticket_unavailable code. Step 5: after release, p95 drops to 3.6 s and the new code is visible in counts.

Percentiles and cost from exported spans

Step 1: export root spans from a local run to JSON Lines with duration_ms and estimated cost. Step 2: compute p50 and p95 with statistics.quantiles. Step 3: sum cost and count outcomes. This is enough for a weekly report without any hosted tool.

python
import json, statistics
from collections import Counter

rows = [json.loads(l) for l in open("spans.jsonl")]
roots = [r for r in rows if r["parent_id"] is None]
ms = [r["duration_ms"] for r in roots]
cuts = statistics.quantiles(ms, n=100)
print("p50", round(cuts[49]), "p95", round(cuts[94]))
print("spend", round(sum(r["app.cost_usd"] for r in roots), 4))
print(Counter(r["app.outcome"] for r in roots).most_common())

Quick reference

  • One trace ID per request; return it to the caller as the request ID
  • Span names: chat + model ID, execute_tool + tool name, and retrieval
  • Content attributes (messages, tool args, query text) are opt-in: keep them off
  • Track p50 and p95, not the mean
  • Fixed outcome codes: answer, abstain, deny, clarify, timeout, unavailable, invalid
  • Cost = sum over model spans of tokens x price; record on the root span
  • Test that a fake email in a request appears in no exported span

Common mistakes

  • Turning on full prompt and response capture in production because it was handy while debugging.
  • Reporting average latency, which hides a slow tail caused by one tool timing out.
  • Counting only errors and missing a steady rise in abstentions after an index change.

Quick quiz

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

Question 1

1Which attribute is safest to record on a retrieval span in production?

Question 2

290 requests take 1 s and 10 take 12 s. Which number best shows the slow tail?

Question 3

3After an index release, errors stay at zero but abstain_no_evidence triples. What is most likely?

Question 4

4What status do the OpenTelemetry GenAI semantic conventions currently have?

0/4 answered

Practice exercises

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

  1. Exercise 1easy

    List six outcome or failure codes for the assistant and one sentence on when each is used.

  2. Exercise 2medium

    Write a function that removes any span attribute whose key is in a deny list or whose value looks like an email address.

  3. Exercise 3hard

    From exported spans (id, parent_id, name, duration_ms), compute for each request the share of time spent in model, retrieval and tool spans.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Do I need a paid observability service?
No. The OpenTelemetry SDK can export to the console or to a local collector and open-source tools such as Jaeger. Hosted services are optional and often have free tiers.
How can I debug a bad answer without logging the text?
Use the request ID to find the trace, then replay the request in a safe environment with the same source IDs, prompt version and model. Store content only in a short-lived, access-controlled debug store if policy allows it.
Should I log token counts for the fixture model?
Yes, so the pipeline is tested end to end, but label cost figures from the fixture as illustrative.

Go deeper

ShareXLinkedInWhatsApp