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

.Net: Bug: Unexpected Accumulation of Previous Assistant Messages in Final Response Using InvokeStreamingAsync

Open nels-ai-source opened this issue 1 year ago • 9 comments

Describe the bug When using the InvokeStreamingAsync method of ChatCompletionAgent, and receiving multi-turn conversation responses in the OnIntermediateMessage, it was found that the final assistant message included previous assistant messages. It appears that the last message accumulates all previous assistant messages. I am not sure if this is a bug, but it has caused confusion during usage.

To Reproduce Steps to reproduce the behavior:

Define a ChatAgent with provided tools.

ChatCompletionAgent agent = new()
{
    Instructions = processRequest.AgentRequest.Instructions,
    Kernel = processRequest.Kernel,
    HistoryReducer = new ChatHistoryTruncationReducer(6, 4),
    Arguments = new KernelArguments(new OpenAIPromptExecutionSettings
    {
        Temperature = 0,
        FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: processRequest.AgentRequest.Functions, autoInvoke: processRequest.AgentRequest.Functions?.Count > 0, options: new() { RetainArgumentTypes = true })
    })
};

Receive messages in OnIntermediateMessage and notice overlapping data. Expected behavior Each message should be independent and non-repetitive.

Platform

Language: C# Source: 1.56.0 IDE: Visual Studio OS: Windows

nels-ai-source avatar Jun 16 '25 08:06 nels-ai-source

@crickman In the ChatCompletionAgent.InternalInvokeStreamingAsync method, the StringBuilder builder accumulates all message content throughout the entire streaming response process. When the method concludes, builder.ToString() is used to create the final assistant message, causing the last message to contain the content of all previous assistant messages.

Image

Problem Analysis:

  1. At line 425, each streaming message is appended to the same StringBuilder: builder.Append(message.ToString())
  2. At line 442, the entire accumulated content is sent as a new message: new(role ?? AuthorRole.Assistant, builder.ToString())

history.json

nels-ai-source avatar Jul 03 '25 07:07 nels-ai-source

@westey-m - Can you review what's going on here and see if it aligns to your intent. I'm not 100% on all of the considerations here.

crickman avatar Jul 17 '25 15:07 crickman

@nels-ai-source, the intent of OnIntermediateMessage is to be able to subscribe to complete messages. This is separate to the streaming responses that you would receive as part of the main InvokeStreamingAsync response. If you consume both you will receive the response text as individual updates via the InvokeStreamingAsync response and as a complete message via OnIntermediateMessage and this is by design.

Is this causing you issues? What problem are you trying to solve?

westey-m avatar Jul 17 '25 17:07 westey-m

Hi @westey-m ,

Thank you very much for your detailed and patient explanation — it was very helpful in understanding the design intent behind OnIntermediateMessage and how it interacts with the streaming response.

I’ve had some time to investigate further, and I’d like to share an observation regarding the final message in the chat history. After the agent.InvokeStreamingAsync call completes, I retrieve the latest message with the role assistant from the thread.ChatHistory. However, I noticed that this final message includes all previous assistant messages, effectively concatenating them into one.

I’ve attached a screenshot for clarity. In the image, you can see that:

The final message in the history contains not just the most recent assistant response, But also includes earlier assistant messages from the same conversation. This behavior leads to duplicated or overlapping content, which can be confusing during usage, especially when building conversation history or persisting messages.

I wanted to confirm whether this is by design or if it might be an unintended side effect of how the messages are collected and stored in the chat history.

Thank you again for your time and support. I truly appreciate it.

Best regards, Image

nels-ai-source avatar Jul 24 '25 01:07 nels-ai-source

@nels-ai-source, thanks for sharing your observations. You are correct that the last message in the chat history is a concatenation of all text from the different streaming updates. This is because chat history consists only out of fully formed messages, and doesn't store separate streaming updates. When streaming, the text from each update is concatenated and at the end, a single message is added to chat history that contains the text from all these updates. There is value to this approach in that it means that your chat history has the same schema for streaming and non-streaming cases.

This behavior leads to duplicated or overlapping content

If there are duplicate or overlapping content in the chat history itself, this may be a bug. Do you have an example of this that you can share with the agent type and model you are using?

westey-m avatar Jul 29 '25 08:07 westey-m

Hi everyone! Same issue here using ChatCompletionAgent.InvokeStreamingAsync. I'd like to be able to filter what is the final response from the stream, so that I can returns to the user just the assistant messages I need to.

In my case the flow is:

  1. user prompt (+ system prompt etc)
  2. 1th LLM call, which returns the first assistant message (here the stream already returns some text)
  3. Tool invocation
  4. 2th LLM call, which returns the final assistant message (here is the right final answer)

Maybe just adding a new field for ContentBlockDeltaEvent (InnerContent) would help.

Note: When using ChatCompletionAgent.InvokeAsync just the last one is returned.

henriqueholtz avatar Aug 01 '25 19:08 henriqueholtz

This issue is stale because it has been open for 90 days with no activity.

github-actions[bot] avatar Apr 23 '26 02:04 github-actions[bot]

This issue is stale because it has been open for 90 days with no activity.

github-actions[bot] avatar Oct 17 '26 01:10 github-actions[bot]

@westey-m a repro that might isolate this: an agent with one function-call turn followed by a final text turn, checking the resulting ChatHistory entry count. If the StringBuilder in InternalInvokeStreamingAsync is only flushed once the whole streaming call completes (rather than at each model-turn boundary), that would explain content from turn N and N+2 merging once a function call happens in between. A fix that wouldn't change the streaming schema: flush the accumulated message as soon as a function-call content block appears, before appending the next turn's deltas.

heitoroliveiranet avatar Oct 22 '26 01:10 heitoroliveiranet