Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions dotnet/src/SemanticKernel.Core/Text/TextChunker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,11 @@ private static List<string> ProcessParagraphs(List<string> paragraphs, int adjus
var lastParagraphTokens = lastParagraph.Split(s_spaceChar, StringSplitOptions.RemoveEmptyEntries);
var secondLastParagraphTokens = secondLastParagraph.Split(s_spaceChar, StringSplitOptions.RemoveEmptyEntries);

var lastParagraphTokensCount = lastParagraphTokens.Length;
var secondLastParagraphTokensCount = secondLastParagraphTokens.Length;
var mergedParagraph = $"{string.Join(" ", secondLastParagraphTokens)} {string.Join(" ", lastParagraphTokens)}";

if (lastParagraphTokensCount + secondLastParagraphTokensCount <= adjustedMaxTokensPerParagraph)
if (GetTokenCount(mergedParagraph, tokenCounter) <= adjustedMaxTokensPerParagraph)
{
var newSecondLastParagraph = string.Join(" ", secondLastParagraphTokens);
var newLastParagraph = string.Join(" ", lastParagraphTokens);

paragraphs[paragraphs.Count - 2] = $"{newSecondLastParagraph} {newLastParagraph}";
paragraphs[paragraphs.Count - 2] = mergedParagraph;
paragraphs.RemoveAt(paragraphs.Count - 1);
}
Comment on lines 195 to 204

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I kept the merge decision on the configured token counter because the whitespace-delimited token array length is the mismatch that caused the bug. This block only runs after the last paragraph is already known to be short, and using word-count short-circuiting for the default path could still disagree with the token counter semantics.

}
Expand Down
11 changes: 11 additions & 0 deletions dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,17 @@ public void CanSplitTextParagraphsWithCustomTokenCounter()
Assert.Equal(expected, result);
}

[Fact]
public void SplitTextParagraphsDoesNotMergeShortLastParagraphPastTokenLimit()
{
var input = new[] { "123456789", "x" };

var result = TextChunker.SplitPlainTextParagraphs(input, 10, tokenCounter: text => text.Length);

Assert.Equal(["123456789", "x"], result);
Assert.All(result, paragraph => Assert.True(paragraph.Length <= 10, $"Paragraph exceeded token limit: {paragraph}"));
}

[Fact]
public void CanSplitTextParagraphsWithOverlapAndCustomTokenCounter()
{
Expand Down
Loading