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
14 changes: 3 additions & 11 deletions dotnet/src/SemanticKernel.Core/Text/TextChunker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ private sealed class StringListWithTokenCount(TextChunker.TokenCounter? tokenCou
/// <returns>The number of tokens in the input string.</returns>
public delegate int TokenCounter(string input);

private static readonly char[] s_spaceChar = [' '];
private static readonly string?[] s_plaintextSplitOptions = ["\n", ".。.", "?!", ";", ":", ",,、", ")]}", " ", "-", null];
private static readonly string?[] s_markdownSplitOptions = [".\u3002\uFF0E", "?!", ";", ":", ",\uFF0C\u3001", ")]}", " ", "-", "\n\r", null];

Expand Down Expand Up @@ -192,18 +191,11 @@ private static List<string> ProcessParagraphs(List<string> paragraphs, int adjus

if (GetTokenCount(lastParagraph, tokenCounter) < adjustedMaxTokensPerParagraph / 4)
{
var lastParagraphTokens = lastParagraph.Split(s_spaceChar, StringSplitOptions.RemoveEmptyEntries);
var secondLastParagraphTokens = secondLastParagraph.Split(s_spaceChar, StringSplitOptions.RemoveEmptyEntries);
var mergedParagraph = $"{secondLastParagraph} {lastParagraph}";

var lastParagraphTokensCount = lastParagraphTokens.Length;
var secondLastParagraphTokensCount = secondLastParagraphTokens.Length;

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);
}
}
Expand Down
15 changes: 15 additions & 0 deletions dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -819,4 +819,19 @@ public void SplitPlainTextParagraphsSplitsWhenExceedingTokenLimit()
Assert.Contains("Second line", combined);
Assert.Contains("Third line", combined);
}

[Fact]
public void SplitPlainTextParagraphsDoesNotMergeOrphanChunkBeyondTokenLimit()
{
var lines = new[]
{
new string('a', 45),
new string('b', 10),
};

var result = TextChunker.SplitPlainTextParagraphs(lines, 52, tokenCounter: input => input.Length);

Assert.Equal(2, result.Count);
Assert.All(result, paragraph => Assert.True(paragraph.Length <= 52));
}
}
Loading