diff --git a/src/Libraries/Microsoft.Extensions.AI/ChatCompletion/OpenTelemetryChatClient.cs b/src/Libraries/Microsoft.Extensions.AI/ChatCompletion/OpenTelemetryChatClient.cs index 3913d33145c..7cf26e5944f 100644 --- a/src/Libraries/Microsoft.Extensions.AI/ChatCompletion/OpenTelemetryChatClient.cs +++ b/src/Libraries/Microsoft.Extensions.AI/ChatCompletion/OpenTelemetryChatClient.cs @@ -201,62 +201,12 @@ public override async IAsyncEnumerable CompleteSt } finally { - TraceCompletion(activity, requestModelId, ComposeStreamingUpdatesIntoChatCompletion(trackedUpdates), error, stopwatch); + TraceCompletion(activity, requestModelId, trackedUpdates.ToChatCompletion(), error, stopwatch); await responseEnumerator.DisposeAsync(); } } - /// Creates a from a collection of instances. - /// - /// This only propagates information that's later used by the telemetry. If additional information from the - /// is needed, this implementation should be updated to include it. - /// - private static ChatCompletion ComposeStreamingUpdatesIntoChatCompletion( - List updates) - { - // Group updates by choice index. - Dictionary> choices = []; - foreach (var update in updates) - { - if (!choices.TryGetValue(update.ChoiceIndex, out var choiceContents)) - { - choices[update.ChoiceIndex] = choiceContents = []; - } - - choiceContents.Add(update); - } - - // Add a ChatMessage for each choice. - string? id = null; - ChatFinishReason? finishReason = null; - string? modelId = null; - List messages = new(choices.Count); - foreach (var choice in choices.OrderBy(c => c.Key)) - { - ChatRole? role = null; - List items = []; - foreach (var update in choice.Value) - { - id ??= update.CompletionId; - finishReason ??= update.FinishReason; - role ??= update.Role; - items.AddRange(update.Contents); - modelId ??= update.ModelId; - } - - messages.Add(new ChatMessage(role ?? ChatRole.Assistant, items)); - } - - return new(messages) - { - CompletionId = id, - FinishReason = finishReason, - ModelId = modelId, - Usage = updates.SelectMany(c => c.Contents).OfType().LastOrDefault()?.Details, - }; - } - /// Creates an activity for a chat completion request, or returns null if not enabled. private Activity? CreateAndConfigureActivity(ChatOptions? options) {