How do you monitor and debug LLM apps and agents in production?

Learning path, stage 5 of 5: Shipping to production · question 5 of 10

Trace every request end to end: the prompt, model and settings, retrieved context, each tool call with its arguments and results, token usage, latency, cost and the final output. Tie each trace to a user session and to feedback. Agents fail in long, branching ways, and without traces you can't tell whether retrieval, the prompt, a tool or the model was at fault.

What to capture

  • Spans per LLM call, tool call and retrieval step, nested under one trace per task.
  • Inputs and outputs (with PII redacted), model ID, settings, stop reason.
  • Usage: input, output and cached tokens, cost, latency (time to first token and total).
  • Quality signals: user feedback, eval scores, guardrail triggers, refusals, retries.

Standards and tools

  • OpenTelemetry GenAI semantic conventions define standard attributes (gen_ai.request.model, gen_ai.usage.input_tokens, and so on), so traces work with any backend.
  • Many LLM observability tools take OTel traces. Pick one that lets you replay a trace as an eval case.

Debugging workflow

Find bad traces (low feedback, errors) → inspect the step where it went wrong → turn it into an eval case → fix → confirm the eval passes.

Sources

Code example

tsx
1// Wrap LLM calls in OpenTelemetry spans with GenAI attributes.
2import { trace, SpanStatusCode } from "@opentelemetry/api";
3import Anthropic from "@anthropic-ai/sdk";
4
5const tracer = trace.getTracer("devqna-ai");
6const client = new Anthropic();
7
8export async function tracedCall(params: Anthropic.MessageCreateParamsNonStreaming) {
9 return tracer.startActiveSpan(`chat ${params.model}`, async (span) => {
10 span.setAttributes({
11 "gen_ai.operation.name": "chat",
12 "gen_ai.provider.name": "anthropic",
13 "gen_ai.request.model": params.model,
14 "gen_ai.request.max_tokens": params.max_tokens,
15 });
16 try {
17 const res = await client.messages.create(params);
18 span.setAttributes({
19 "gen_ai.response.model": res.model,
20 "gen_ai.response.finish_reasons": [res.stop_reason ?? "unknown"],
21 "gen_ai.usage.input_tokens": res.usage.input_tokens,
22 "gen_ai.usage.output_tokens": res.usage.output_tokens,
23 });
24 return res;
25 } catch (e) {
26 span.recordException(e as Error);
27 span.setStatus({ code: SpanStatusCode.ERROR });
28 throw e;
29 } finally {
30 span.end();
31 }
32 });
33}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @opentelemetry/api vitest, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app