semantic-kernel icon indicating copy to clipboard operation
semantic-kernel copied to clipboard

.Net: Fix non-streaming function calling text and usage aggregation

Open Cozmopolit opened this issue 11 months ago • 0 comments

Motivation and Context

Fixes #13420

When using auto function invocation in non-streaming mode (GetChatMessageContentAsync), intermediate text content generated by the LLM before tool calls is silently discarded. Additionally, token usage is not aggregated across multiple API calls in the auto-invoke loop.

Problem: If the LLM responds with "Let me check that for you..." before requesting a tool call, and then provides a final answer after the tool result, only the final answer is returned. The intermediate text is lost.

Scenario: Users relying on non-streaming mode with auto function invocation expect to receive all text the LLM generated, not just the final response.

Description

This PR modifies the non-streaming auto function calling loop in all three affected connectors to:

  1. Aggregate text content across all loop iterations using a StringBuilder
  2. Aggregate token usage (InputTokens + OutputTokens) across all API calls
  3. Apply aggregated state to the final response, including when a filter terminates early

Affected Connectors:

Connector File
OpenAI / Azure OpenAI Connectors.OpenAI/Core/ClientCore.ChatCompletion.cs
Google / Gemini Connectors.Google/Core/Gemini/Clients/GeminiChatCompletionClient.cs
MistralAI Connectors.MistralAI/Client/MistralClient.cs

Implementation approach:

  • Before the loop: Initialize aggregatedContent (StringBuilder) and token counters
  • Each iteration: Accumulate text (with \n\n separator) and token counts
  • On exit: Prepend aggregated text to final message and add AggregatedUsage metadata (only when multiple iterations occurred)

Out of Scope:

  • MEAI-based connectors (Azure AI Inference, Ollama) - they already handle this correctly via FunctionInvokingChatClient
  • Python SDK - separate issue/PR needed

New Tests

Added 5 unit tests for the OpenAI connector in FunctionCallingContentAggregationTests.cs:

Test Description
NonStreaming_IntermediateTextBeforeToolCall_IsAggregatedInFinalResponseAsync Verifies text before tool calls is preserved
NonStreaming_TokenUsage_IsAggregatedAcrossAllIterationsAsync Verifies AggregatedUsage metadata contains sum of all tokens
NonStreaming_SingleIteration_NoAggregationMetadataAddedAsync Verifies no regression for single-iteration calls
NonStreaming_ToolCallWithoutIntermediateText_OnlyFinalTextReturnedAsync Verifies empty intermediate text is handled correctly
NonStreaming_FilterTerminatesEarly_AggregatedContentStillAppliedAsync Verifies aggregation works when filter terminates

Contribution Checklist

Cozmopolit avatar Dec 22 '25 17:12 Cozmopolit