diff --git a/.github/workflows/build-samples.yml b/.github/workflows/build-samples.yml
index b630030..6f70a7d 100644
--- a/.github/workflows/build-samples.yml
+++ b/.github/workflows/build-samples.yml
@@ -9,6 +9,7 @@ on:
- "dotnet-ai/agent-framework-incident-triage/**"
- "dotnet-ai/mcp-server-csharp-dotnet/**"
- "dotnet-ai/microsoft-extensions-ai-evaluation/**"
+ - "dotnet-ai/opentelemetry-ai-observability/**"
- "dotnet-aspire/orchestrate-distributed-system/**"
- "software-architecture/architecture-testing-dotnet/**"
- "distributed-systems/transactional-outbox-ef-core/**"
@@ -43,6 +44,7 @@ on:
- "dotnet-ai/agent-framework-incident-triage/**"
- "dotnet-ai/mcp-server-csharp-dotnet/**"
- "dotnet-ai/microsoft-extensions-ai-evaluation/**"
+ - "dotnet-ai/opentelemetry-ai-observability/**"
- "dotnet-aspire/orchestrate-distributed-system/**"
- "software-architecture/architecture-testing-dotnet/**"
- "distributed-systems/transactional-outbox-ef-core/**"
@@ -2139,3 +2141,26 @@ jobs:
dotnet run --project src/EvaluationRunner --configuration Release --no-build --no-restore -- --repaired . "$RUNNER_TEMP/evaluation-repaired.md"
diff -u reports/candidate-scorecard.md "$RUNNER_TEMP/evaluation-candidate.md"
diff -u reports/repaired-scorecard.md "$RUNNER_TEMP/evaluation-repaired.md"
+
+ test-opentelemetry-ai-observability:
+ name: Test .NET AI OpenTelemetry sample
+ runs-on: ubuntu-latest
+ timeout-minutes: 12
+
+ defaults:
+ run:
+ working-directory: dotnet-ai/opentelemetry-ai-observability
+
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+
+ - name: Install verified .NET SDK
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: "10.0.404"
+
+ - name: Verify offline traces, metrics, and payload exclusion
+ run: bash verify.sh --offline
diff --git a/README.md b/README.md
index 4c5bcbe..39e290f 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,7 @@ Each sample folder contains a focused implementation of one tutorial topic. The
| [`dotnet-ai/agent-framework-incident-triage`](dotnet-ai/agent-framework-incident-triage/) | Evidence-first Microsoft Agent Framework sample with read-only tools, deterministic incident evidence, `AgentSession` reuse, and correlation-vs-causation boundaries | [Microsoft Agent Framework Tutorial in C#: Build a Tool-Using AI Agent](https://www.dotnet-guide.com/tutorials/dotnet-ai/agent-framework-incident-triage/) |
| [`dotnet-ai/mcp-server-csharp-dotnet`](dotnet-ai/mcp-server-csharp-dotnet/) | .NET 10 MCP stdio server with three read-only tools, deterministic JSON-backed data, real client discovery/invocation, protocol error verification, and deterministic tests | [Build Your First MCP Server in C# and .NET](https://www.dotnet-guide.com/tutorials/dotnet-ai/mcp-server-csharp-dotnet/) |
| [`dotnet-ai/microsoft-extensions-ai-evaluation`](dotnet-ai/microsoft-extensions-ai-evaluation/) | Offline prompt regression testing across 12 incidents and five hard checks, with optional live evaluation | Tutorial in preparation. [Browse .NET AI tutorials](https://www.dotnet-guide.com/tutorials/dotnet-ai/) |
+| [`dotnet-ai/opentelemetry-ai-observability`](dotnet-ai/opentelemetry-ai-observability/) | .NET 10 traces and metrics for model calls, tool execution, and a downstream Evidence API, with deterministic tests and optional Jaeger and live-model runs | Tutorial in preparation. [Browse .NET AI tutorials](https://www.dotnet-guide.com/tutorials/dotnet-ai/) |
| [`dotnet-aspire/orchestrate-distributed-system`](dotnet-aspire/orchestrate-distributed-system/) | Minimal Aspire AppHost coordinating a web project and API with service discovery and startup ordering | [Aspire in .NET: Orchestrate, Run, and Deploy a Distributed System from One App Host](https://www.dotnet-guide.com/tutorials/dotnet-aspire/orchestrate-distributed-system/) |
| [`software-architecture/architecture-testing-dotnet`](software-architecture/architecture-testing-dotnet/) | Minimal NetArchTest.eNhancedEdition rule that prevents Domain from depending on outer layers | [Architecture Testing in .NET: Enforce Layer and Module Boundaries with NetArchTest and ArchUnitNET](https://www.dotnet-guide.com/tutorials/software-architecture/architecture-testing-dotnet/) |
| [`distributed-systems/transactional-outbox-ef-core`](distributed-systems/transactional-outbox-ef-core/) | Minimal EF Core and SQLite demonstration that saves business state and an outbox message atomically, then publishes it through a one-shot relay | [Transactional Outbox Pattern in .NET with EF Core (.NET 10): Fix the Dual-Write Problem](https://www.dotnet-guide.com/tutorials/distributed-systems/transactional-outbox-ef-core/) |
diff --git a/dotnet-ai/opentelemetry-ai-observability/.gitignore b/dotnet-ai/opentelemetry-ai-observability/.gitignore
new file mode 100644
index 0000000..76f8799
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/.gitignore
@@ -0,0 +1,2 @@
+/results.*/
+__pycache__/
diff --git a/dotnet-ai/opentelemetry-ai-observability/NuGet.Config b/dotnet-ai/opentelemetry-ai-observability/NuGet.Config
new file mode 100644
index 0000000..5485860
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/NuGet.Config
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx b/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx
new file mode 100644
index 0000000..e61a1fa
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx
@@ -0,0 +1,3 @@
+
+
+
diff --git a/dotnet-ai/opentelemetry-ai-observability/README.md b/dotnet-ai/opentelemetry-ai-observability/README.md
new file mode 100644
index 0000000..3e7157e
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/README.md
@@ -0,0 +1,55 @@
+# Observe .NET AI Apps with OpenTelemetry
+
+Follow one request through ASP.NET Core, `IChatClient`, tool invocation, a custom evidence lookup span, and a downstream HTTP service. This .NET 10 companion runs Triage and Evidence as two separate Kestrel processes from one executable.
+
+| Scenario | Evidence API | Triage API | What to inspect |
+| --- | --- | --- | --- |
+| Healthy | 200 | 200 | Eight connected spans across two services |
+| Slow | 200 after a 1.2 s delay | 200 | Evidence accounts for the extra dependency and tool time |
+| Failed | 503 | 200 with `evidenceAvailable: false` | Trace shows the downstream failure and the controlled response |
+
+## Run the offline verification
+
+Use .NET SDK 10.0.404, Bash, and Python 3.10+ on Linux. Package restore uses NuGet. The run uses a scripted chat client and a local SDK exporter.
+
+```bash
+cd dotnet-ai/opentelemetry-ai-observability
+bash verify.sh --offline
+```
+
+The verifier runs two requests per scenario, checks the trace structure and metrics, scans both signals for synthetic payload markers, and runs a separate capture-enabled build to prove the scanner can detect known content. Look for `results.*/verification.log`.
+
+## Inspect the traces in Jaeger
+
+```bash
+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
+```
+
+Open [Jaeger](http://127.0.0.1:16686) and use the trace IDs in the generated `jaeger-summary.json`. Open the slow trace and follow **Execute Tool → Evidence Lookup → HTTP GET → Evidence API**. In the failed trace, compare the Evidence 503 with the Triage 200. Both are part of one trace.
+
+The Jaeger backend stores traces in memory. Use `docker compose -f docker/compose.yaml down` when you finish browsing.
+
+## Optional live run
+
+Start [llama.cpp b7124](https://github.com/ggml-org/llama.cpp/releases/tag/b7124) with the [Qwen3-0.6B Q8_0 model](https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/tree/23749fefcc72300e3a2ad315e1317431b06b590a). Keep Jaeger running and use a second terminal for the verifier.
+
+```bash
+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}'
+```
+
+```bash
+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 maps the first model's schema-constrained action to a .NET function call and supplies the resulting evidence to a second model request. Its two model HTTP calls add two spans per trace. Token counts in the live probe come from the provider.
+
+## Further reading
+
+- [Trace contract](docs/trace-contract.md)
+- [Metrics and telemetry privacy](docs/metrics-and-privacy.md)
+- [Verified environment](docs/verified-environment.md)
+- [.NET AI tutorials on DOTNET GUIDE](https://www.dotnet-guide.com/tutorials/dotnet-ai/)
diff --git a/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml b/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml
new file mode 100644
index 0000000..c58e4fb
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml
@@ -0,0 +1,12 @@
+services:
+ jaeger:
+ image: cr.jaegertracing.io/jaegertracing/jaeger@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e
+ command: ["--config", "/dotnet-guide-jaeger.yaml"]
+ environment:
+ DG_JAEGER_QUERY_LISTEN: 0.0.0.0:16686
+ DG_JAEGER_OTLP_LISTEN: 0.0.0.0:4318
+ ports:
+ - "127.0.0.1:16686:16686"
+ - "127.0.0.1:4318:4318"
+ volumes:
+ - "./jaeger.yaml:/dotnet-guide-jaeger.yaml:ro"
diff --git a/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml b/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml
new file mode 100644
index 0000000..0149ce0
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml
@@ -0,0 +1,35 @@
+service:
+ extensions: [jaeger_storage, jaeger_query]
+ pipelines:
+ traces:
+ receivers: [otlp]
+ exporters: [jaeger_storage_exporter]
+ telemetry:
+ metrics:
+ level: none
+ logs:
+ level: info
+
+extensions:
+ jaeger_storage:
+ backends:
+ local_traces:
+ memory:
+ max_traces: 1000
+ jaeger_query:
+ storage:
+ traces: local_traces
+ http:
+ endpoint: "${env:DG_JAEGER_QUERY_LISTEN:-127.0.0.1:16686}"
+ grpc:
+ endpoint: 127.0.0.1:0
+
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: "${env:DG_JAEGER_OTLP_LISTEN:-127.0.0.1:4318}"
+
+exporters:
+ jaeger_storage_exporter:
+ trace_storage: local_traces
diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md b/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md
new file mode 100644
index 0000000..5d077a1
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md
@@ -0,0 +1,15 @@
+# Metrics and telemetry privacy
+
+| Instrument | Unit | Use |
+| --- | --- | --- |
+| `http.server.request.duration` | seconds | Compare the Triage and Evidence server views. Route templates and status codes are dimensions. |
+| `http.client.request.duration` | seconds | Inspect dependency time and downstream HTTP status. When exporting to Jaeger, the exporter POST is a separate series from the Evidence GET. |
+| `gen_ai.client.operation.duration` | seconds | Measure the two chat operations. |
+| `gen_ai.client.token.usage` | tokens | Measure reported input and output token usage. The offline counts are synthetic. |
+| `dotnet_guide.evidence.lookup.duration` | seconds | Group by `available` or `unavailable`. The unavailable series count measures failed lookups. |
+
+The AI instrument names describe the pinned Microsoft.Extensions.AI version. The demo exports its metrics to local JSON. Jaeger is used for traces. The console proofs check counts, tags, units, and timing ranges.
+
+The normal pipeline explicitly sets `EnableSensitiveData = false`. The offline harness sets the framework capture environment flag to true and requires the synthetic prompt, answer, tool argument, tool result, and evidence markers to stay out of trace and metric snapshots. A separate compile-time control captures synthetic content so the test verifies that all five markers can be found. The control and its artifacts live in test output. This verifies the sample's instrumented paths under the tested configuration. It is not a guarantee about every possible request, provider, or exporter.
+
+HTTP response proofs include artificial sample content for test assertions. Use the SDK and Jaeger trace captures to inspect exported telemetry.
diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md b/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md
new file mode 100644
index 0000000..6efe7aa
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md
@@ -0,0 +1,24 @@
+# Trace contract
+
+Triage receives `POST /triage/{incidentId}` and uses `UseFunctionInvocation().UseOpenTelemetry(...)` to observe the two model calls and the evidence tool. The custom `dotnet-guide.triage.evidence_lookup` span wraps the HTTP dependency call. Evidence handles `GET /evidence/{incidentId}` in its own process.
+
+```mermaid
+flowchart TD
+ Triage["Triage API"] --> Flow["orchestrate_tools"]
+ Flow --> First["First model call"]
+ Flow --> Tool["Evidence tool"]
+ Flow --> Last["Final model call"]
+ Tool --> Lookup["Evidence lookup"]
+ Lookup --> Client["Outbound HTTP"]
+ Client --> Evidence["Evidence API"]
+```
+
+All eight scripted spans have one trace ID and distinct span IDs. The two services report independent service names. Evidence's server span has the outbound HTTP span ID as its parent. The live probe adds an HTTP client child below each model call.
+
+| Scenario | Expected behavior |
+| --- | --- |
+| Healthy | Evidence records E-201 and E-101. The scripted answer states the cause is unconfirmed. The custom lookup has status `Ok`. |
+| Slow | The Evidence API waits 1.2 s and returns the healthy evidence. The duration increase is visible in the downstream span and aggregate metrics. |
+| Failed | An empty HTTP 503 marks the Evidence server, outbound client, lookup, and tool spans as errors. Triage returns HTTP 200 with no evidence and the cause unconfirmed. The root span has status `Unset`. |
+
+Nested span durations can overlap. Use their position within a trace to locate the delay. The trace verifier checks exact span counts so duplicate instrumentation is visible.
diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md b/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md
new file mode 100644
index 0000000..b0a5fbd
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md
@@ -0,0 +1,13 @@
+# Verified environment
+
+| Component | Verified version |
+| --- | --- |
+| .NET SDK and target | 10.0.404, `net10.0` |
+| Microsoft.Extensions.AI | 11.0.1 |
+| OpenTelemetry .NET | 1.21.0 |
+| Jaeger | 2.23.0, Linux amd64 |
+| Optional local inference | llama.cpp b7124, Qwen3-0.6B Q8_0 |
+
+The offline tests exercise actual loopback HTTP between two processes. They require Bash and Python and use no model API key or telemetry backend. The Jaeger and live modes are separate integration checks. Jaeger queries compare stored trace and span IDs, parents, service names, statuses, times, and selected attributes with the application's local captures.
+
+The sample is designed to teach trace topology and operational diagnosis. Treat the artificial delay, token counts from the scripted model, and demonstration privacy canaries as test fixtures.
diff --git a/dotnet-ai/opentelemetry-ai-observability/global.json b/dotnet-ai/opentelemetry-ai-observability/global.json
new file mode 100644
index 0000000..1f4a137
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/global.json
@@ -0,0 +1,7 @@
+{
+ "sdk": {
+ "version": "10.0.404",
+ "rollForward": "disable",
+ "allowPrerelease": false
+ }
+}
diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs
new file mode 100644
index 0000000..b788efe
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs
@@ -0,0 +1,62 @@
+using System.Diagnostics;
+using System.Diagnostics.Metrics;
+using System.Net;
+
+internal static class EvidenceLookup
+{
+ public const string SourceName = "DotnetGuide.Triage";
+ public const string ActivityName = "dotnet-guide.triage.evidence_lookup";
+
+ public const string DurationInstrumentName = "dotnet_guide.evidence.lookup.duration";
+ private const string OutcomeKey = "dotnet_guide.evidence.outcome";
+
+ private static readonly ActivitySource Source = new(SourceName);
+ private static readonly Meter Meter = new(SourceName);
+ private static readonly Histogram LookupDuration =
+ Meter.CreateHistogram(DurationInstrumentName, unit: "s", description: "Time spent looking up incident evidence.");
+
+ public static async Task GetAsync(
+ HttpClient client, string incidentId, CancellationToken cancellation)
+ {
+ using Activity? lookup = Source.StartActivity(ActivityName, ActivityKind.Internal);
+ long started = Stopwatch.GetTimestamp();
+ string? outcome = null;
+ try
+ {
+ using var response = await client.GetAsync($"evidence/{Uri.EscapeDataString(incidentId)}", cancellation);
+ lookup?.SetTag("dotnet_guide.evidence.http_status_code", (int)response.StatusCode);
+ if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
+ {
+ outcome = "unavailable";
+ lookup?.SetTag(OutcomeKey, outcome);
+ lookup?.SetTag("error.type", "evidence_unavailable");
+ lookup?.SetStatus(ActivityStatusCode.Error);
+ return null;
+ }
+
+ response.EnsureSuccessStatusCode();
+ EvidenceReply reply = await response.Content.ReadFromJsonAsync(cancellation)
+ ?? throw new InvalidOperationException("Missing Evidence response.");
+ outcome = "available";
+ lookup?.SetTag(OutcomeKey, outcome);
+ lookup?.SetStatus(ActivityStatusCode.Ok);
+ return reply;
+ }
+ catch (Exception) when (!cancellation.IsCancellationRequested)
+ {
+ outcome = "unavailable";
+ lookup?.SetTag(OutcomeKey, outcome);
+ lookup?.SetTag("error.type", "lookup_failed");
+ lookup?.SetStatus(ActivityStatusCode.Error);
+ throw;
+ }
+ finally
+ {
+ if (outcome is not null)
+ {
+ LookupDuration.Record(Stopwatch.GetElapsedTime(started).TotalSeconds,
+ new KeyValuePair(OutcomeKey, outcome));
+ }
+ }
+ }
+}
diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs
new file mode 100644
index 0000000..ebd2c33
--- /dev/null
+++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs
@@ -0,0 +1,178 @@
+using System.Net.Http.Json;
+using System.Text.Json;
+using Microsoft.Extensions.AI;
+
+internal sealed class LiveChatClient(HttpClient http, Uri endpoint, string model) : IChatClient
+{
+ public const string PromptMarker = "DG_OBSERVABILITY_PROMPT_CANARY";
+ public const string ToolArgumentMarker = "DG_OBSERVABILITY_TOOL_ARGUMENT_CANARY";
+ public const string ToolResultMarker = "DG_OBSERVABILITY_TOOL_RESULT_CANARY";
+ public const string EvidenceMarker = "DG_OBSERVABILITY_EVIDENCE_BODY_CANARY";
+ public const string ToolName = "lookup_evidence";
+ public const string TurnKey = "dotnet-guide.live-turn";
+
+ private readonly ChatClientMetadata metadata = new("llama.cpp", endpoint, model);
+
+ public async Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (options?.AdditionalProperties?.TryGetValue(TurnKey, out object? state) != true || state is not LiveTurn turn)
+ {
+ throw new InvalidOperationException("The live request did not provide turn state.");
+ }
+
+ ChatMessage[] transcript = messages.ToArray();
+ var toolResult = transcript.SelectMany(message => message.Contents).OfType().SingleOrDefault();
+ bool hasToolResult = toolResult is not null;
+ if (hasToolResult)
+ {
+ var supplied = JsonSerializer.Deserialize(toolResult!.Result?.ToString() ?? "null");
+ turn.SawToolResult = supplied?.ProbeMarker == ToolResultMarker;
+ turn.SawEvidence = supplied?.Evidence?.Contains(EvidenceMarker, StringComparison.Ordinal) == true;
+ if (!turn.SawToolResult || supplied!.Available != turn.SawEvidence)
+ {
+ throw new InvalidOperationException("The completed tool turn did not supply the expected evidence state.");
+ }
+ }
+ turn.SawPrompt |= transcript.Any(message => message.Role == ChatRole.User
+ && message.Text.Contains(PromptMarker, StringComparison.Ordinal));
+ var payload = new Dictionary
+ {
+ ["model"] = model,
+ ["messages"] = transcript.SelectMany(ToWireMessages).ToArray(),
+ ["temperature"] = 0,
+ ["max_tokens"] = 128,
+ ["seed"] = 17,
+ ["stream"] = false,
+ };
+ if (!hasToolResult)
+ {
+ payload["messages"] = transcript.SelectMany(ToWireMessages)
+ .Append(new { role = "user", content = "Choose the lookup_evidence action before answering. Return the action as JSON." })
+ .ToArray();
+ payload["response_format"] = new
+ {
+ type = "json_schema",
+ json_schema = new
+ {
+ name = "evidence_action",
+ schema = new
+ {
+ type = "object",
+ properties = new
+ {
+ action = new { type = "string", @enum = new[] { ToolName } },
+ incident = new { type = "string", @enum = new[] { turn.IncidentId } },
+ note = new { type = "string", @enum = new[] { ToolArgumentMarker } },
+ },
+ required = new[] { "action", "incident", "note" },
+ additionalProperties = false,
+ },
+ },
+ };
+ }
+
+ using HttpResponseMessage response = await http.PostAsJsonAsync(endpoint, payload, cancellationToken);
+ response.EnsureSuccessStatusCode();
+ await using Stream body = await response.Content.ReadAsStreamAsync(cancellationToken);
+ using JsonDocument document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken);
+ JsonElement data = document.RootElement;
+ JsonElement choice = data.GetProperty("choices")[0];
+ JsonElement message = choice.GetProperty("message");
+ string? text = message.TryGetProperty("content", out JsonElement content) && content.ValueKind is JsonValueKind.String
+ ? content.GetString() : null;
+ string? finish = choice.GetProperty("finish_reason").GetString();
+ string? responseModel = data.GetProperty("model").GetString();
+ string responseId = data.GetProperty("id").GetString()
+ ?? throw new InvalidOperationException("The provider did not supply a response ID.");
+
+ AIContent part;
+ if (!hasToolResult)
+ {
+ using JsonDocument action = JsonDocument.Parse(text
+ ?? throw new InvalidOperationException("The model returned an empty action."));
+ JsonElement item = action.RootElement;
+ if (item.GetProperty("action").GetString() != ToolName)
+ {
+ throw new InvalidOperationException("The generated action did not name the registered tool.");
+ }
+
+ part = new FunctionCallContent(responseId, ToolName, new Dictionary
+ {
+ ["incident"] = item.GetProperty("incident").GetString(),
+ ["note"] = item.GetProperty("note").GetString(),
+ });
+ }
+ else
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ throw new InvalidOperationException("The model returned an empty answer.");
+ }
+ part = new TextContent(text);
+ }
+
+ UsageDetails? usage = null;
+ if (data.TryGetProperty("usage", out JsonElement usageData) && usageData.ValueKind == JsonValueKind.Object)
+ {
+ usage = new UsageDetails
+ {
+ InputTokenCount = ReadCount(usageData, "prompt_tokens"),
+ OutputTokenCount = ReadCount(usageData, "completion_tokens"),
+ TotalTokenCount = ReadCount(usageData, "total_tokens"),
+ };
+ }
+ turn.Calls.Add(new(responseId, responseModel, finish, usage?.InputTokenCount,
+ usage?.OutputTokenCount, usage?.TotalTokenCount));
+ return new ChatResponse(new ChatMessage(ChatRole.Assistant, [part]))
+ {
+ ModelId = responseModel,
+ ResponseId = responseId,
+ FinishReason = !hasToolResult ? ChatFinishReason.ToolCalls : finish switch
+ {
+ "length" => ChatFinishReason.Length,
+ _ => ChatFinishReason.Stop,
+ },
+ Usage = usage,
+ };
+ }
+
+ private static long? ReadCount(JsonElement usage, string name) =>
+ usage.TryGetProperty(name, out JsonElement value) && value.TryGetInt64(out long count) ? count : null;
+
+ private static IEnumerable