Observability for LLM features and agents: OpenTelemetry GenAI semantic conventions, UseOpenTelemetry in Microsoft.Extensions.AI, spans for model and tool calls, token and cost metrics, content capture and PII, Application Insights and Aspire dashboards, quality signals and alerting.
Treat every model and tool call as a dependency in your distributed trace. In .NET, IChatClient pipelines get .UseOpenTelemetry(), which emits spans and metrics following the OpenTelemetry GenAI semantic conventions: a chat {model} span per model call with model, input and output tokens, finish reason, and an execute_tool {name} span per tool call, under the agent or request span. From those I build token, latency (including time to first token) and cost metrics attributed per feature and tenant. Prompt and response content is off by default because it often holds personal data; when I need it, I capture a redacted sample with short retention. On top I add quality signals: user feedback, sampled groundedness and safety evaluations, tool error rates and iterations per run. The trade-off: richer capture makes debugging easy but creates a privacy and cost liability.
"I want an AI request to look like any other request in Application Insights: one trace with the HTTP request, the model calls, the tool calls and the database queries under it. In .NET that's mostly configuration. I add
.UseOpenTelemetry()to theIChatClientpipeline andAddSource/AddMeterfor the Microsoft.Extensions.AI sources in the OpenTelemetry setup, and I export with the Azure Monitor distro or OTLP. Each model call becomes achatspan tagged with the GenAI semantic conventions: model, input and output token counts, finish reason.FunctionInvokingChatClientadds anexecute_toolspan per tool call, so I can see exactly which tool ran with which call id, how long it took and whether it failed. The conventions are still marked Development in late 2026, so I pin the version and expect attribute names to move.From that I derive the metrics that matter: tokens and cost per feature and per tenant, p95 latency and time to first token, throttling (429s) per deployment, iterations per agent run and tool error rates. For example, at [company] a cost dashboard by feature showed that [a summarisation job] was [60%] of our spend because it re-sent the full document on every retry; fixing the retry policy cut the bill by […]. Content is the hard part. Prompts and responses contain whatever the user typed, so content capture is off by default. When we need it for quality investigations, we capture a small redacted sample into a separate store with [14-day] retention and restricted access.
The mistake I see is logging full prompts into the main log store 'for debugging', which turns observability into a data breach waiting to happen. My rule: trace everything structural, capture content deliberately."
| Signal | Where | Why |
|---|---|---|
Model call span (chat {model}) |
Trace | Latency, model, tokens, finish reason per call |
Tool call span (execute_tool {name}) |
Trace | Which tool, duration, errors, call id |
| Agent / workflow span | Trace | Groups the loop; iterations per run |
| Token usage histogram | Metric | Cost and capacity per feature and tenant |
| Operation duration, time to first token | Metric | User-perceived latency, streaming health |
| 429 / retry counts | Metric | Quota exhaustion per deployment |
| Prompt / response content | Separate, opt-in, redacted | Quality debugging only |
| Feedback, evaluation scores | Metric / events | Quality over time |
| Dashboard panel | Alert |
|---|---|
| Cost per day by feature and tenant | Daily cost > 150% of 7-day average |
| p95 latency and time to first token | p95 above SLO for 15 min |
| 429 rate per deployment | > 2% of calls for 10 min |
| Iterations per agent run (p99) | p99 at the cap: likely loops |
| Tool error rate by tool | > 5% for 15 min |
| Groundedness / thumbs-down rate | Drop beyond a threshold after a release |
After adding GenAI spans and a cost-by-tenant dashboard, we found [one tenant's integration] calling the assistant in a retry loop, responsible for [35%] of tokens; a per-tenant budget alert fired within [20 minutes] of the next spike and the cap stopped it.
Checks whether the candidate can make AI features operable: traces, token and cost metrics, quality signals, and privacy-safe handling of prompt content.
Green flags
UseOpenTelemetry and the GenAI semantic conventions, aware they are still evolvingRed flags
POST /assistant/ask 1.9 s
└─ invoke_agent booking-assistant 1.8 s
├─ chat gpt-4.1-mini in=2,310 out=45 0.6 s finish=tool_calls
├─ execute_tool list_my_bookings 0.08 s
│ └─ SQL SELECT Bookings ... 0.03 s
├─ chat gpt-4.1-mini in=2,690 out=120 0.9 s finish=stop
└─ (content not captured)
The GenAI conventions define operation names (chat, embeddings, execute_tool, invoke_agent), attributes such as gen_ai.operation.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons, gen_ai.tool.name and gen_ai.tool.call.id, and metrics such as gen_ai.client.token.usage and gen_ai.client.operation.duration. As of late 2026 they are in Development status and, since June 2026, maintained in a separate semantic-conventions-genai repository, so names can change between versions.
OpenTelemetryChatClient (added with .UseOpenTelemetry()) wraps each call in an Activity from an ActivitySource and records metrics on a Meter. FunctionInvokingChatClient creates activities for tool invocations. The Agent Framework adds agent-level spans. Your OpenTelemetry setup must subscribe to those sources and meters; the Azure Monitor OpenTelemetry distro or an OTLP exporter sends them to Application Insights, the Aspire dashboard or any OTLP backend. EnableSensitiveData controls whether message content is recorded; it defaults to false.
Providers bill per input and output token, with lower prices for cached input on some models. Compute cost from token metrics and a price table in configuration (prices change), tagged with feature, tenant and model. Keep tenant and user ids out of high-cardinality metric dimensions where they would explode cost; use tenant (bounded) on metrics and user only on traces or logs.
Prompts carry user input, retrieved documents and tool results; responses can echo them. Under the Privacy Act (APP 11) you must protect personal information you hold, including in logs, and a leak can trigger the Notifiable Data Breaches scheme. Options: no content (default); hashed or length-only content; redacted samples (PII detection before storage) in a separate workspace with short retention and restricted RBAC; full capture only in non-production with synthetic data.
Latency and errors don't tell you the answer was right. Add: explicit user feedback linked to the trace id; offline evaluation runs per release; online sampled evaluation (groundedness, relevance, safety) using Microsoft.Extensions.AI.Evaluation or Azure AI Foundry evaluations; and proxy metrics such as escalation rate and approval rejection rate.
AI spans are a small fraction of total spans but very valuable. Use tail-based sampling in the OpenTelemetry Collector to keep all traces with errors, high cost or many iterations, and sample normal ones.
.UseOpenTelemetry() to an IChatClient, run under .NET Aspire and inspect the GenAI spans and token metrics in the dashboard.EnableSensitiveData in a dev environment and see what content appears; then decide what you'd allow in production.OpenTelemetry for an AI feature: GenAI spans and metrics, content off, cost per feature recorded as a custom metric.
// Program.cs (.NET 10)
using Azure.Monitor.OpenTelemetry.AspNetCore;
using Microsoft.Extensions.AI;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
const string AiSource = "Contoso.Assistant.AI"; // our own source name for the chat client telemetry
builder.Services.AddOpenTelemetry()
.UseAzureMonitor() // connection string from configuration, not code
.WithTracing(t => t.AddSource(AiSource, "Microsoft.Extensions.AI*", "Microsoft.Agents.AI*"))
.WithMetrics(m => m.AddMeter(AiSource, "Microsoft.Extensions.AI*", AiCostMeter.Name));
builder.Services.AddSingleton<AiCostMeter>();
builder.Services.AddChatClient(sp => sp.GetRequiredService<AzureOpenAIClient>()
.GetChatClient(builder.Configuration["AI:ChatDeployment"]!).AsIChatClient())
.UseFunctionInvocation()
.UseOpenTelemetry(sourceName: AiSource, configure: o => o.EnableSensitiveData = false); // no prompt content
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.AI;
namespace Contoso.Assistant;
// Cost in AUD per feature and tenant, from token usage and a configurable price table.
public sealed class AiCostMeter(IConfiguration config)
{
public const string Name = "Contoso.Assistant.Cost";
private static readonly Meter Meter = new(Name);
private static readonly Counter<double> Cost = Meter.CreateCounter<double>("ai.cost", unit: "AUD");
public void Record(ChatResponse response, string feature, string tenantId)
{
if (response.Usage is not { } usage) return;
var model = response.ModelId ?? "unknown";
var inPrice = config.GetValue<double>($"AI:Prices:{model}:InputPerMillion");
var outPrice = config.GetValue<double>($"AI:Prices:{model}:OutputPerMillion");
double aud = (usage.InputTokenCount ?? 0) * inPrice / 1_000_000
+ (usage.OutputTokenCount ?? 0) * outPrice / 1_000_000;
Cost.Add(aud, new("feature", feature), new("tenant", tenantId), new("model", model));
Activity.Current?.SetTag("app.ai.cost_aud", aud); // also on the trace for drill-down
}
}
// Application Insights: tokens and calls per model per day
dependencies
| where timestamp > ago(7d) and name startswith "chat "
| extend model = tostring(customDimensions["gen_ai.request.model"]),
inTok = toint(customDimensions["gen_ai.usage.input_tokens"]),
outTok = toint(customDimensions["gen_ai.usage.output_tokens"])
| summarize calls = count(), input = sum(inTok), output = sum(outTok), p95 = percentile(duration, 95)
by model, bin(timestamp, 1d)
AI observability is ordinary observability plus two things: cost is now a per-request runtime metric, and the payload is often personal data. I want structural telemetry on 100% of AI calls (cheap and safe) and content on a small, governed sample. The other senior point is that correctness needs its own signal, so I wire feedback and evaluation into the same dashboards as latency.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Application Insights via Azure Monitor distro | Azure-hosted .NET, one place for everything | Ingestion cost; sample normal traffic | Strict multi-cloud or self-hosted requirement |
| OTLP to Grafana / Tempo / Prometheus | Existing open-source stack | Run and scale it yourself | Small team without platform support |
| Dedicated LLM observability tool | Heavy prompt iteration, evaluation workflows | Another vendor holding prompt data | When data residency or privacy rules forbid it |
| Aspire dashboard | Local development and testing | Free, not persistent | Production |
Head sampling decides at the start of a trace: the root service keeps, say, 10%, and the decision travels in the traceparent sampled flag so every service records the same traces. In .NET that's ParentBasedSampler(new TraceIdRatioBasedSampler(0.1)). It's cheap, but it decides before knowing whether the request will fail.
Tail sampling decides after the trace completes: the OpenTelemetry Collector buffers spans (about 30 s), then keeps all errors, all traces slower than a threshold, and a small random baseline. It needs every span of a trace on the same Collector, so you route by trace id with the loadbalancing exporter, and it costs memory.
Always compute metrics before sampling, so dashboards and alerts stay accurate. The trade-off: head sampling is simple and cheap; tail sampling keeps the interesting traces but adds infrastructure you must run.
Treat every prompt, index and log as a copy of your data with its own access controls. Minimise and redact personal information before it goes into a prompt. In RAG, enforce tenant and permission filters inside the search query (or separate indexes); never trust the model to withhold something it was given. Logs and traces are the leak people forget: don't capture prompt content by default, and redact and limit retention when you do.
Know where the provider processes and stores data: deployment region, Global vs regional deployments, and abuse-monitoring retention. Map it to the Privacy Act: APP 6 purpose, APP 8 cross-border, APP 11 security, the NDB scheme, and automated-decision transparency from December 2026. The trade-off: more context improves answers but widens what can leak.
Activity is .NET's span type and ActivitySource is the factory that creates them, the equivalent of an OpenTelemetry Tracer. They live in System.Diagnostics, so libraries can emit spans without referencing OpenTelemetry at all. You call source.StartActivity("name", ActivityKind.Internal) inside a using, add tags (attributes), events and a status, and disposing it records the duration.
StartActivity returns null when nothing is listening or the sampler drops the span, which is why you write activity?.SetTag(...). The OpenTelemetry SDK only listens to sources registered with AddSource("MyCompany.Orders"). Activity.Current is stored in an AsyncLocal, flows across await, and becomes the parent of the next activity.
The trade-off: the API is free when tracing is off, but you must name sources consistently or your spans silently go nowhere.
How to tell it (STAR)
**S:** Our Azure OpenAI spend tripled overnight and interactive users started seeing throttling errors, but we only had endpoint-level telemetry. **T:** I needed to find the cause fast and make sure we'd see it coming next time. **A:** I turned on OpenTelemetry for every chat client with a feature tag, and within [an hour] the GenAI spans showed a nightly summary job re-sending [40k-token] prompts on every 429 with no backoff. We paused it, fixed the retry policy, moved batch work to its own deployment, and built a cost-by-feature dashboard with an alert. **R:** Spend returned to baseline the next day, interactive throttling dropped to [under 0.5%], and the alert has since caught [two] smaller regressions within minutes.
Last updated 23 Nov 2026.