Skip to content

.Net: Bug: ChatHistoryTruncationReducer and ChatHistorySummarizationReducer throw ArgumentOutOfRangeException when targetCount is 1 and the history has a system message #14654

Open

Description

Describe the bug
ChatHistoryTruncationReducer and ChatHistorySummarizationReducer throw ArgumentOutOfRangeException from ReduceAsync when they are created with targetCount: 1 and the chat history contains a system message. Both constructors accept targetCount: 1.

ChatHistoryReducerExtensions.LocateSafeReductionIndex subtracts one from targetCount for the system message. With targetCount: 1 the value becomes 0, so the truncation index is chatHistory.Count, and the function-content check reads chatHistory[chatHistory.Count].

To Reproduce

ChatHistory history = new("You are a helpful assistant.");
history.AddUserMessage("Hello");
history.AddAssistantMessage("Hi");
history.AddUserMessage("How are you?");

var reducer = new ChatHistoryTruncationReducer(targetCount: 1);
await reducer.ReduceAsync(history); // throws
System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
   at Microsoft.SemanticKernel.ChatCompletion.ChatHistoryReducerExtensions.LocateSafeReductionIndex(...)
   at Microsoft.SemanticKernel.ChatCompletion.ChatHistoryTruncationReducer.ReduceAsync(...)

ChatHistorySummarizationReducer with targetCount: 1 fails the same way. From the code, a reducer used through ChatHistoryAgent.HistoryReducer would hit the same exception once the history grows past the target.

Expected behavior
The reducer keeps the system message and the most recent message (plus the summary for the summarization reducer) instead of throwing.

Platform

  • Language: C#
  • Source: main branch of repository
  • AI model: N/A
  • IDE: N/A
  • OS: Linux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETIssue or Pull requests regarding .NET codetriage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions