From 429b97cdedb6815bfc8c60eaaa9684cb8eea828c Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 25 Oct 2026 17:23:03 +0330 Subject: [PATCH] add TextChunker Service for AI Project ... --- Configurations/XAiApiConfiguration.cs | 5 + DI/XDIHelperExtension.cs | 29 ++ Extensions/XModelsExtensions.cs | 22 +- Interfaces/IXTextChunker.cs | 32 ++ Models/XTextChunk.cs | 38 ++ Models/XTextChunkerDescriptor.cs | 33 ++ Providers/XTextChunker.cs | 588 ++++++++++++++++++++++++++ Startup.cs | 10 +- appsettings.Development.json | 9 +- 9 files changed, 760 insertions(+), 6 deletions(-) create mode 100644 Interfaces/IXTextChunker.cs create mode 100644 Models/XTextChunk.cs create mode 100644 Models/XTextChunkerDescriptor.cs create mode 100644 Providers/XTextChunker.cs diff --git a/Configurations/XAiApiConfiguration.cs b/Configurations/XAiApiConfiguration.cs index 17ea4b0..9507155 100644 --- a/Configurations/XAiApiConfiguration.cs +++ b/Configurations/XAiApiConfiguration.cs @@ -35,5 +35,10 @@ namespace xAiApi.Configurations /// /// public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new(); + + /// + /// Text Chunker Configuration ... + /// + public XTextChunkerDescriptor TextChunker { get; set; } = new(); } } \ No newline at end of file diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 5337058..2dfea23 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -1,6 +1,8 @@ using System; using xAiApi.Constants; +using xAiApi.Providers; using xAiApi.Extensions; +using xAiApi.Interfaces; using xAiApi.Middlewares; using xCommons.Extensions; using xAiApi.Configurations; @@ -71,6 +73,20 @@ namespace xAiApi.DI source.AddSingleton(configuration); } + /// + /// Register Ai Services ... + /// + /// + public static void AddXAiServices( + this IServiceCollection source + ) + { + // + source.AddScoped(); + source.AddScoped(); + source.AddScoped(); + } + /// /// Register AiApi File Content Extractor Services ... /// @@ -99,6 +115,19 @@ namespace xAiApi.DI source.AddSingleton(); } + /// + /// Register AiApi Text Chunker Service ... + /// + /// + public static void AddXAiTextChunker( + this IServiceCollection source + ) + { + // + // Stateless -> Singleton ... + source.AddSingleton(); + } + /// /// Use Model Proxy Provider ... /// diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs index 4bdbf3f..b88af7a 100644 --- a/Extensions/XModelsExtensions.cs +++ b/Extensions/XModelsExtensions.cs @@ -15,6 +15,7 @@ using xExceptions.Constants; using Microsoft.Extensions.AI; using System.Collections.Generic; using System.ClientModel.Primitives; +using xAiApi.Models; namespace xAiApi.Extensions { @@ -36,7 +37,26 @@ namespace xAiApi.Extensions source.Prompts.Any(p => p.Name .Equals( XAiApiConstants.XAiApiIntroductionPromptName, - System.StringComparison.InvariantCultureIgnoreCase)); + StringComparison.InvariantCultureIgnoreCase)); + + // + return result; + } + + /// + /// Check TextChunker Descriptor is Valid or not ... + /// + /// + /// + public static bool IsValid(this XTextChunkerDescriptor source) + { + // + var result = + source.ChunkSize > 0 && + source.ChunkOverlap >= 0 && + source.ChunkOverlap < source.ChunkSize && + source.MinChunkSize >= 0 && + source.MinChunkSize <= source.ChunkSize; // return result; diff --git a/Interfaces/IXTextChunker.cs b/Interfaces/IXTextChunker.cs new file mode 100644 index 0000000..e854a0a --- /dev/null +++ b/Interfaces/IXTextChunker.cs @@ -0,0 +1,32 @@ +using xAiApi.Models; +using System.Collections.Generic; + +namespace xAiApi.Interfaces +{ + /// + /// a Service for Splitting Long Texts into Overlapping Chunks + /// which Suitable for Embedding ... + /// + public interface IXTextChunker + { + /// + /// Split Text into Chunks ... + /// + /// Source Text + /// Source Name (e.g. File Name) used for Identifier + /// + IList Chunk( + string text, + string source = null + ); + + /// + /// Split Text into Chunks and Return only Texts ... + /// + /// + /// + IList ChunkTexts( + string text + ); + } +} diff --git a/Models/XTextChunk.cs b/Models/XTextChunk.cs new file mode 100644 index 0000000..eda1182 --- /dev/null +++ b/Models/XTextChunk.cs @@ -0,0 +1,38 @@ +namespace xAiApi.Models +{ + /// + /// Represents a Chunk of a Text which Produced by Text Chunker ... + /// + public class XTextChunk + { + /// + /// Zero Based Index of Chunk in Source Text ... + /// + public int Index { get; set; } + + /// + /// Chunk Text Content ... + /// + public string Text { get; set; } = string.Empty; + + /// + /// Source Name (e.g. File Name) which Chunk Extracted From ... + /// + public string Source { get; set; } + + /// + /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... + /// + public string Identifier { get; set; } + + /// + /// Start Offset of Chunk in Normalized Source Text ... + /// + public int StartOffset { get; set; } + + /// + /// Length of Chunk Text ... + /// + public int Length => Text?.Length ?? 0; + } +} diff --git a/Models/XTextChunkerDescriptor.cs b/Models/XTextChunkerDescriptor.cs new file mode 100644 index 0000000..d440d22 --- /dev/null +++ b/Models/XTextChunkerDescriptor.cs @@ -0,0 +1,33 @@ +namespace xAiApi.Models +{ + /// + /// Text Chunker Descriptor ... + /// + public class XTextChunkerDescriptor + { + /// + /// Maximum Characters Count of each Chunk ... + /// + public int ChunkSize { get; set; } = 800; + + /// + /// Characters Count which Shared between two Consecutive Chunks ... + /// + public int ChunkOverlap { get; set; } = 150; + + /// + /// Chunks Smaller than this Size will be Merged into Previous Chunk ... + /// + public int MinChunkSize { get; set; } = 50; + + /// + /// Chunck Identifier Separator ... + /// + public string ChunkIdentifierSeparator { get; set; } = "#"; + + /// + /// Normalize Line Endings and Repeated Whitespaces before Chunking ... + /// + public bool NormalizeWhitespace { get; set; } = true; + } +} diff --git a/Providers/XTextChunker.cs b/Providers/XTextChunker.cs new file mode 100644 index 0000000..a505c2f --- /dev/null +++ b/Providers/XTextChunker.cs @@ -0,0 +1,588 @@ +using System.Linq; +using System.Text; +using xAiApi.Models; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Extensions; +using xAiApi.Configurations; +using xExceptions.Constants; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace xAiApi.Providers +{ + /// + /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy: + /// Paragraphs -> Sentences -> Words -> Hard Cut ... + /// + public class XTextChunker : IXTextChunker + { + /// + /// Default Options which used when no Options Provided ... + /// + private readonly XAiApiConfiguration configuration; + + /// + /// Matches Paragraph Boundaries (two or more Line Breaks) ... + /// + private static readonly Regex ParagraphSplitter = new( + @"\n\s*\n+", + RegexOptions.Compiled + ); + + /// + /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ... + /// + private static readonly Regex SentenceSplitter = new( + @"(?<=[\.\!\?؟。!?])\s+|(?<=\n)", + RegexOptions.Compiled + ); + + /// + /// Matches Repeated Horizontal Whitespaces ... + /// + private static readonly Regex HorizontalWhitespace = new( + @"[ \t\f\v\u00A0]{2,}", + RegexOptions.Compiled + ); + + /// + /// Matches Three or more Line Breaks ... + /// + private static readonly Regex ExcessiveLineBreaks = new( + @"\n{3,}", + RegexOptions.Compiled + ); + + public XTextChunker( + XAiApiConfiguration configuration + ) + { + // + // Validate Configuration ... + if ( + !configuration.IsValid() || + !configuration.TextChunker.IsValid() + ) + { + XException.InvalidConfiguration.Throw(); + } + + // + this.configuration = configuration; + } + + /// + /// Split Text into Chunks ... + /// + /// + /// + /// + public IList Chunk( + string text, + string source = null + ) + { + // + var result = new List(); + if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text)) + { + return result; + } + + // + // Normalize ... + var normalized = configuration.TextChunker.NormalizeWhitespace + ? Normalize(text) + : text; + + // + // Short Circuit for Small Texts ... + if (normalized.Length <= configuration.TextChunker.ChunkSize) + { + // + result.Add(CreateChunk(normalized, 0, 0, source)); + return result; + } + + // + // Build Atomic Units (never larger than ChunkSize) ... + var units = BuildUnits(normalized); + + // + // Accumulate Units into Chunks with Overlap ... + var chunks = Accumulate(units); + + // + // Merge too Small Tail Chunks ... + chunks = MergeSmallChunks(chunks); + + // + for (var i = 0; i < chunks.Count; i++) + { + result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source)); + } + + // + return result; + } + + /// + /// Split Text into Chunks and Return only Texts ... + /// + /// + /// + public IList ChunkTexts(string text) + { + // + var result = Chunk(text, null) + .Select(c => c.Text) + .ToList(); + + // + return result; + } + + // + #region Private ... + /// + /// Internal Text Unit with its Offset in Normalized Source ... + /// + private readonly struct Unit + { + public Unit(string text, int offset) + { + Text = text; + Offset = offset; + } + + public string Text { get; } + public int Offset { get; } + } + + /// + /// Normalize Line Endings and Whitespaces ... + /// + /// + /// + private string Normalize(string text) + { + // + var result = text + .Replace("\r\n", "\n") + .Replace('\r', '\n'); + + // + result = HorizontalWhitespace.Replace(result, " "); + result = ExcessiveLineBreaks.Replace(result, "\n\n"); + + // + result = result.Trim(); + + // + return result; + } + + /// + /// Create Chunk Model ... + /// + /// + /// + /// + /// + /// + private XTextChunk CreateChunk( + string text, + int offset, + int index, + string source + ) + { + // + var identifier = source.IsNullOrEmpty() + ? index.ToString() + : $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}"; + + // + var result = new XTextChunk + { + Text = text, + Index = index, + Source = source, + StartOffset = offset, + Identifier = identifier + }; + + // + return result; + } + + /// + /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ... + /// + /// + /// + private List BuildUnits(string text) + { + // + var result = new List(); + + // + foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0)) + { + // + if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize) + { + // + result.Add(paragraph); + continue; + } + + // + // Paragraph too Long -> Sentences ... + foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset)) + { + // + if (sentence.Text.Length <= configuration.TextChunker.ChunkSize) + { + // + result.Add(sentence); + continue; + } + + // + // Sentence too Long -> Word Boundary Hard Cut ... + result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize)); + } + } + + // + return result; + } + + /// + /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ... + /// + /// + /// + /// + /// + private IEnumerable SplitWithOffsets( + string text, + Regex splitter, + int baseOffset + ) + { + // + var position = 0; + foreach (Match match in splitter.Matches(text)) + { + // + var part = text.Substring(position, match.Index - position); + var unit = TrimUnit(part, baseOffset + position); + if (!unit.Text.IsNullOrEmpty()) + { + yield return unit; + } + + // + position = match.Index + match.Length; + } + + // + if (position < text.Length) + { + // + var tail = TrimUnit(text.Substring(position), baseOffset + position); + if (!tail.Text.IsNullOrEmpty()) + { + yield return tail; + } + } + } + + /// + /// Trim Unit Text while Adjusting its Offset ... + /// + /// + /// + /// + private Unit TrimUnit( + string text, + int offset + ) + { + // + var start = 0; + while (start < text.Length && char.IsWhiteSpace(text[start])) + { + start++; + } + + // + var end = text.Length; + while (end > start && char.IsWhiteSpace(text[end - 1])) + { + end--; + } + + // + var result = new Unit(text.Substring(start, end - start), offset + start); + + // + return result; + } + + /// + /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ... + /// + /// + /// + /// + private IEnumerable HardSplit( + Unit unit, + int maxSize + ) + { + // + var text = unit.Text; + var position = 0; + + // + while (position < text.Length) + { + // + var remaining = text.Length - position; + if (remaining <= maxSize) + { + // + yield return TrimUnit(text.Substring(position), unit.Offset + position); + yield break; + } + + // + // Find Last Whitespace within Window ... + var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize); + if (cut <= position) + { + // + // No Whitespace -> Hard Cut ... + cut = position + maxSize; + } + + // + var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position); + if (!piece.Text.IsNullOrEmpty()) + { + yield return piece; + } + + // + position = cut; + while (position < text.Length && char.IsWhiteSpace(text[position])) + { + position++; + } + } + } + + /// + /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ... + /// + /// + /// + private List Accumulate(List units) + { + // + var result = new List(); + if (!units.HasChild()) + { + return result; + } + + // + var buffer = new StringBuilder(); + var buffered = new List(); + var bufferOffset = -1; + + // + foreach (var unit in units) + { + // + var separator = buffer.Length > 0 ? " " : string.Empty; + var projected = buffer.Length + separator.Length + unit.Text.Length; + + // + if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0) + { + // + // Close Current Chunk ... + var closed = buffer.ToString(); + result.Add(new Unit(closed, bufferOffset)); + + // + // Seed Next Chunk with Overlap Tail (only if Unit still Fits) ... + var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap); + var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize; + + // + buffer.Clear(); + if (!overlap.IsNullOrEmpty() && fits) + { + // + bufferOffset = ComputeOverlapOffset(buffered, overlap.Length); + buffer.Append(overlap); + separator = " "; + } + else + { + // + bufferOffset = -1; + separator = string.Empty; + } + + // + buffered.Clear(); + } + + // + if (bufferOffset < 0) + { + bufferOffset = unit.Offset; + } + + // + buffer.Append(separator).Append(unit.Text); + buffered.Add(unit); + } + + // + if (buffer.Length > 0) + { + result.Add(new Unit(buffer.ToString(), bufferOffset)); + } + + // + return result; + } + + /// + /// Map Trailing Overlap Length of Buffered Units back to Source Offset ... + /// Units Joined by Single Space Separator in Buffer ... + /// + /// + /// + /// + private int ComputeOverlapOffset( + List buffered, + int overlapLength + ) + { + // + var result = 0; + var remaining = overlapLength; + for (var i = buffered.Count - 1; i >= 0; i--) + { + // + var unit = buffered[i]; + if (remaining <= unit.Text.Length) + { + // + result = unit.Offset + unit.Text.Length - remaining; + return result; + } + + // + // Consume Unit and its Leading Separator ... + remaining -= unit.Text.Length + 1; + if (remaining <= 0) + { + // + result = unit.Offset; + return result; + } + } + + // + result = buffered.Count > 0 ? buffered[0].Offset : 0; + + // + return result; + } + + /// + /// Take Trailing Overlap from Text, Aligned to Word Boundary ... + /// + /// + /// + /// + private string TakeOverlap( + string text, + int overlap + ) + { + // + if (overlap <= 0 || text.Length <= overlap) + { + return string.Empty; + } + + // + var start = text.Length - overlap; + var boundary = text.IndexOfAny(WordBoundaries, start); + if (boundary < 0 || boundary >= text.Length - 1) + { + // + // No Boundary inside Window -> Skip Overlap ... + return string.Empty; + } + + // + return text.Substring(boundary + 1).Trim(); + } + + /// + /// Merge Chunks Smaller than MinChunkSize into their Predecessor ... + /// + /// + /// + private List MergeSmallChunks(List chunks) + { + // + if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2) + { + return chunks; + } + + // + var result = new List(); + foreach (var chunk in chunks) + { + // + if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0) + { + // + var previous = result[result.Count - 1]; + var merged = $"{previous.Text} {chunk.Text}"; + if (merged.Length <= configuration.TextChunker.ChunkSize) + { + result[result.Count - 1] = new Unit(merged, previous.Offset); + continue; + } + } + + // + result.Add(chunk); + } + + // + return result; + } + + /// + /// Characters Considered as Word Boundaries ... + /// + private readonly char[] WordBoundaries = [' ', '\n', '\t']; + #endregion + } +} diff --git a/Startup.cs b/Startup.cs index 1163aa9..7b1ccf1 100644 --- a/Startup.cs +++ b/Startup.cs @@ -190,10 +190,12 @@ namespace xAiApi services.AddXAiFileContentExtractors(); // - // Register Default Ai Service ... - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + // Register Text Chunker Service ... + services.AddXAiTextChunker(); + + // + // Register Default AI Services ... + services.AddXAiServices(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) diff --git a/appsettings.Development.json b/appsettings.Development.json index e708a50..db5104e 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -105,6 +105,13 @@ "ProxyConfiguration": { "Enabled": true, "RoutePrefix": "/ai-model" + }, + "TextChunker": { + "ChunkSize": 800, + "ChunkOverlap": 150, + "MinChunkSize": 50, + "NormalizeWhitespace": true, + "ChunkIdentifierSeparator": "#" } }, "Logging": { @@ -115,4 +122,4 @@ } }, "AllowedHosts": "*" -} +} \ No newline at end of file