Skip to content

Commit d4e2f42

Browse files
Fix TextChunker token-counted paragraph merge
1 parent 2fb749e commit d4e2f42

2 files changed

Lines changed: 45 additions & 2 deletions

File tree

dotnet/src/SemanticKernel.Core/Text/TextChunker.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,13 @@ private static List<string> ProcessParagraphs(List<string> paragraphs, int adjus
202202
{
203203
var newSecondLastParagraph = string.Join(" ", secondLastParagraphTokens);
204204
var newLastParagraph = string.Join(" ", lastParagraphTokens);
205+
var mergedParagraph = $"{newSecondLastParagraph} {newLastParagraph}";
205206

206-
paragraphs[paragraphs.Count - 2] = $"{newSecondLastParagraph} {newLastParagraph}";
207-
paragraphs.RemoveAt(paragraphs.Count - 1);
207+
if (GetTokenCount(mergedParagraph, tokenCounter) <= adjustedMaxTokensPerParagraph)
208+
{
209+
paragraphs[paragraphs.Count - 2] = mergedParagraph;
210+
paragraphs.RemoveAt(paragraphs.Count - 1);
211+
}
208212
}
209213
}
210214
}

dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,45 @@ public void CanSplitTextParagraphsWithCustomTokenCounter()
558558
Assert.Equal(expected, result);
559559
}
560560

561+
[Fact]
562+
public void SplitPlainTextParagraphsWithCustomTokenCounterDoesNotMergePastTokenLimit()
563+
{
564+
List<string> input =
565+
[
566+
"abcdefghijklmnopqr",
567+
"abc"
568+
];
569+
570+
var expected = new[]
571+
{
572+
"abcdefghijklmnopqr",
573+
"abc"
574+
};
575+
576+
var result = TextChunker.SplitPlainTextParagraphs(input, 20, tokenCounter: static (input) => input.Length);
577+
578+
Assert.Equal(expected, result);
579+
}
580+
581+
[Fact]
582+
public void SplitPlainTextParagraphsWithCustomTokenCounterStillMergesWhenCandidateFits()
583+
{
584+
List<string> input =
585+
[
586+
"abcdefghijklmnop",
587+
"abc"
588+
];
589+
590+
var expected = new[]
591+
{
592+
"abcdefghijklmnop abc"
593+
};
594+
595+
var result = TextChunker.SplitPlainTextParagraphs(input, 20, tokenCounter: static (input) => input.Length);
596+
597+
Assert.Equal(expected, result);
598+
}
599+
561600
[Fact]
562601
public void CanSplitTextParagraphsWithOverlapAndCustomTokenCounter()
563602
{

0 commit comments

Comments
 (0)