.Net: Fix non-streaming function calling text and usage aggregation
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:
- Aggregate text content across all loop iterations using a
StringBuilder - Aggregate token usage (InputTokens + OutputTokens) across all API calls
- 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\nseparator) and token counts - On exit: Prepend aggregated text to final message and add
AggregatedUsagemetadata (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
- [x] The code builds clean without any errors or warnings
- [x] The PR follows the SK Contribution Guidelines and the pre-submission formatting script raises no violations
- [x] All unit tests pass, and I have added new tests where possible
- [x] I didn't break anyone :smile: