Skip to main content

Observe .NET AI Apps with OpenTelemetry

Trace a .NET AI request from the model through a tool and a downstream API. Use OpenTelemetry and Jaeger to find where time went, follow an HTTP 503, and verify what telemetry captures.

Start with the trace

A Triage request returns HTTP 200, yet the Evidence API underneath it returns HTTP 503. The trace shows where the dependency failed, how the tool recorded it, and why the final response contains no evidence.

The lab sends one question about a checkout incident from the Triage API through a model, a tool, and a second ASP.NET Core process. Its two evidence records show a deployment at 14:02 UTC and a checkout error spike at 14:09 UTC. The cause is unconfirmed.

Expected outcomes by scenario
ScenarioTriageEvidenceWhat to look for
Healthy200200Eight connected spans across both services.
Slow200200 after a 1.2 s injected delayThe extra time is visible in the Evidence server span.
Failed200 with evidenceAvailable: false503Four downstream spans record an error.

Run the sample offline

Use Linux, Bash, Python 3.10 or later, and .NET SDK 10.0.404. The sample pins this exact SDK and requests packages from NuGet during restore. Its default ScriptedChatClient uses no model endpoint, API key, or Docker.

Shell · clone and run the verified sample
git clone https://github.com/dotnet-guide-com/tutorials.git
cd tutorials
git checkout c88f578e1ebd6737bb4ea9e047181e57f526358b
cd dotnet-ai/opentelemetry-ai-observability
bash verify.sh --offline

The verifier runs each scenario twice over loopback HTTP, using separate Kestrel processes for Triage and Evidence. The verification log prints the specific results.* directory. Inside it, each scenario has a triage/ and evidence/ directory with spans.jsonl and metrics.json.

Verifier · final line
PASS deterministic topology, slow path, Evidence 503 fallback, metrics, and privacy

The failed scenario passes when the expected dependency failure and fallback are both observed. Read the offline verifier to see what each check requires.

Read the eight-span trace

A trace ID identifies the whole request. Each span has its own span ID, and the parent span ID tells you which operation started it. The span tree below is the scripted path. The first chat requests the tool, and the final chat consumes the tool result. The two chat spans and the tool share the same orchestration parent.

Parent-child relationships in the scripted trace
  • POST /triage/{incidentId} Triage server
    • orchestrate_tools
      • chat scripted-model First model call
      • execute_tool lookup_evidence
        • dotnet-guide.triage.evidence_lookup
          • GET Outbound HTTP client
            • GET /evidence/{incidentId} Evidence server
      • chat scripted-model Final model call

Find dotnet-guide-triage-api and dotnet-guide-evidence-api in the trace's service resources. The Evidence server span's parent ID should match the outbound GET span's ID. This link shows that trace context crossed the HTTP boundary. See the sample trace contract for the expected status on each path.

Register the AI and HTTP instrumentation

UseFunctionInvocation() runs the registered tool within the chat turn. UseOpenTelemetry() supplies the AI instrumentation. The normal pipeline explicitly disables sensitive data capture when it builds the shared IChatClient.

C# · application chat pipeline
var pipeline = new ChatClientBuilder(inner).UseFunctionInvocation();
pipeline.UseOpenTelemetry(configure: telemetry => telemetry.EnableSensitiveData = false);
return pipeline.Build();
Where each span comes from
RegistrationSpan boundary
AddAspNetCoreInstrumentation()Incoming requests on both API processes.
AddHttpClientInstrumentation()Triage's outbound request to Evidence, plus its model HTTP requests in live mode.
AddSource("Experimental.Microsoft.Extensions.AI")Chat operations and function invocation from the pinned AI package.
AddSource("DotnetGuide.Triage")The custom lookup activity that wraps the downstream dependency call.

Keep the activity source registrations in tracing and the corresponding AddMeter(...) registrations in metrics. The sample defines a fixed service name for each process and configures OTLP only when a local endpoint is supplied. See service registration and the lookup span.

Send the traces to Jaeger

With Docker Compose installed, use the checked-in configuration to start the pinned Jaeger 2.23.0 image. The first address below is the UI and query service. The second is the OTLP/HTTP trace receiver.

Shell · start Jaeger and verify OTLP export
docker compose -f docker/compose.yaml up -d
bash verify.sh --jaeger http://127.0.0.1:16686 http://127.0.0.1:4318/v1/traces
  1. Find the results.* directory printed by this run and open its jaeger-summary.json.
  2. Copy a trace ID from healthy, slow, or failed. Open local Jaeger and visit /trace/<trace-id> on that host.
  3. Expand the tool, lookup, and outbound HTTP spans until the Evidence server span appears. Select a span to inspect its tags and status.

Jaeger stores traces in memory in this configuration. Stop it with docker compose -f docker/compose.yaml down after you finish investigating. The verifier also saves the query responses in jaeger/ under the run directory.

Find the slow operation

Compare the slow trace with the healthy one using the same span path. The Evidence API deliberately waits 1.2 seconds before returning the same evidence. That wait appears in the Evidence server span and in its enclosing HTTP client, lookup, and tool spans.

Healthy and slow requests on a shared 0–2,000 ms scale

Healthy

  • Triage request285 ms
  • Evidence tool140 ms
  • Custom lookup123 ms
  • Outbound HTTP108 ms
  • Evidence API57 ms

Slow

  • Triage request1,513 ms
  • Evidence tool1,346 ms
  • Custom lookup1,325 ms
  • Outbound HTTP1,304 ms
  • Evidence API1,269 ms

Selected spans from the first healthy and first slow trace of a verified local Jaeger run. Bars start relative to the Triage request.

Follow the time into the Evidence server span before investigating model latency. Nested spans share elapsed time. Adding the tool, HTTP client, and server durations would count the same wait more than once. Treat the illustrated durations as a local capture. Machine load and startup overhead affect the exact values.

Follow a dependency failure through a successful request

In the failed scenario, Evidence returns an empty HTTP 503. The tool returns an unavailable result, so Triage can finish with HTTP 200 and an explicit fallback. This is the sample's application contract.

JSON · selected fields from the scripted fallback
{
  "evidenceAvailable": false,
  "answer": "Evidence is unavailable. The cause is unconfirmed.",
  "evidence": null
}

The root Triage span has status Unset. The Evidence server, outbound HTTP client, custom lookup, and tool spans record Error. The tool still hands back a structured unavailable result, so the final chat can complete. Inspect both http.response.status_code and the span status to see the distinction.

Use metrics to compare repeated requests

Start with the trace to explain one request. Then compare the local histogram snapshots to see whether the same behavior repeats. The scripted run records two lookups and four model operations per scenario. Its synthetic token totals are 44 input and 28 output tokens per scenario.

Verified histogram instruments
InstrumentWhat to compare
http.server.request.durationSeconds by service, route, and HTTP status.
http.client.request.durationSeconds for Evidence GET requests. OTLP export POSTs form a separate series when Jaeger is enabled.
gen_ai.client.operation.durationSeconds per model call.
gen_ai.client.token.usageInput and output token observations from the provider or scripted client.
dotnet_guide.evidence.lookup.durationSeconds by available or unavailable. Use the unavailable histogram count to count failed lookups.

For a single histogram point with a nonzero count, sum / count gives its mean. Compare matching series and keep the units in view. Use the sample's metrics and privacy notes for the exact instruments and scope.

Verify content stays out of exported telemetry

The test sends distinct synthetic markers through the prompt, answer, tool arguments, tool result, and Evidence body. The regular build must keep them out of its captured spans and metrics even with the environment capture flag enabled. A separate scripted, local-only build enables capture so the verifier can prove it detects all five marker classes.

Inspect spans.jsonl and metrics.json for telemetry. The http-request.json and http-responses.json files are synthetic test witnesses and can contain the marker values. Keep the capture control local and use synthetic data with it.

Production boundary. The checks cover the sample's instrumented paths and tested configuration. Review the attributes, payload capture, sampling, destination, and retention settings for your own application before exporting telemetry.

Check the trace contract in CI

The repository workflow installs the pinned SDK and runs bash verify.sh --offline. The job checks exact span counts and parentage, downstream outcomes, timing bounds for the synthetic delay, metric values, and payload exclusion. The offline job uses SDK captures, so it can run without Jaeger or a live model.

All 31 checks passed on the published merge commit. The OpenTelemetry job is the hosted proof for the automated offline checks. The local Jaeger and live-model capture were verified separately.

Optional live-model run

Keep Jaeger running. Start the pinned llama.cpp b7124 server with the Qwen3-0.6B Q8_0 weights. Replace the model path with your downloaded file.

Shell · serve Qwen locally
llama-server --host 127.0.0.1 --port 8080 --model /path/to/Qwen3-0.6B-Q8_0.gguf \
  --alias qwen3-0.6b --ctx-size 2048 --threads 4 --parallel 1 \
  --jinja --chat-template-kwargs '{"enable_thinking":false}' 

From another terminal in the sample folder, run:

Shell · verify model and Evidence spans
bash verify.sh --live http://127.0.0.1:16686 http://127.0.0.1:4318/v1/traces \
  http://127.0.0.1:8080/v1/chat/completions qwen3-0.6b

The live adapter translates a schema-constrained model action into the .NET tool call. Two outbound HTTP calls to llama.cpp add one child span under each chat operation. The verified run captured ten spans per scenario and compared the provider-reported token counts with the exported metrics.

Troubleshooting

The requested SDK is missing

Run dotnet --list-sdks and install SDK 10.0.404. The sample's global.json disables roll-forward.

Jaeger shows no traces

Check docker compose -f docker/compose.yaml ps, then rerun the Jaeger verifier. Use port 16686 to query traces and the full http://127.0.0.1:4318/v1/traces URL to receive them.

Only HTTP spans appear

Check that the tracing provider subscribes to Experimental.Microsoft.Extensions.AI and DotnetGuide.Triage and that the chat client uses the instrumented pipeline.

Evidence looks like a separate trace

Compare the two trace IDs and check whether the Evidence span's parent matches the outbound client's span ID. Verify that the HTTP boundary propagates W3C trace context.

Frequently asked questions

Does the offline run need an API key or Jaeger?

The offline run uses a scripted chat client and a local SDK exporter. NuGet access is needed for restore.

Why can the root request return HTTP 200 when Evidence returns 503?

The Triage API handles unavailable evidence as a controlled fallback. The failed operation is still visible in the dependency and tool spans.

Does Jaeger show the sample’s metrics?

The sample sends traces to Jaeger. Its metric snapshots are written to the local run directory.

How do I identify the model calls?

Look for the two chat spans beneath orchestrate_tools. In live mode, each chat span has an outbound model HTTP child.

Official references

Version note. The verified sample targets net10.0 with SDK 10.0.404, Microsoft.Extensions.AI 11.0.1, and OpenTelemetry 1.21.0. Check the verified environment when comparing instrumentation from a different version.

Verified dotnet-guide.com companion sample

The repository includes the two service roles, the scripted and live chat adapters, the Jaeger configuration, and the verification scripts. Commit c88f578 is the version used in this walkthrough.

Independent educational sample. dotnet-guide.com is an independent educational publisher. The expected topology, failure policy, and capture checks are teaching choices for this lab.

Continue with the Evidence-First Incident Triage Agent for tool and evidence design, or Evaluate .NET AI Apps with Microsoft.Extensions.AI.Evaluation for behavioral regression checks.