add TextChunker Service for AI Project ...

This commit is contained in:
2026-10-25 17:23:03 +03:30
parent 4b857de518
commit 429b97cded
9 changed files with 760 additions and 6 deletions
+5
View File
@@ -35,5 +35,10 @@ namespace xAiApi.Configurations
/// </summary>
/// <returns></returns>
public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new();
/// <summary>
/// Text Chunker Configuration ...
/// </summary>
public XTextChunkerDescriptor TextChunker { get; set; } = new();
}
}
+29
View File
@@ -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);
}
/// <summary>
/// Register Ai Services ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiServices(
this IServiceCollection source
)
{
//
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
source.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
}
/// <summary>
/// Register AiApi File Content Extractor Services ...
/// </summary>
@@ -99,6 +115,19 @@ namespace xAiApi.DI
source.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
}
/// <summary>
/// Register AiApi Text Chunker Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiTextChunker(
this IServiceCollection source
)
{
//
// Stateless -> Singleton ...
source.AddSingleton<IXTextChunker, XTextChunker>();
}
/// <summary>
/// Use Model Proxy Provider ...
/// </summary>
+21 -1
View File
@@ -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;
}
/// <summary>
/// Check TextChunker Descriptor is Valid or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
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;
+32
View File
@@ -0,0 +1,32 @@
using xAiApi.Models;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
/// <summary>
/// a Service for Splitting Long Texts into Overlapping Chunks
/// which Suitable for Embedding ...
/// </summary>
public interface IXTextChunker
{
/// <summary>
/// Split Text into Chunks ...
/// </summary>
/// <param name="text">Source Text</param>
/// <param name="source">Source Name (e.g. File Name) used for Identifier</param>
/// <returns></returns>
IList<XTextChunk> Chunk(
string text,
string source = null
);
/// <summary>
/// Split Text into Chunks and Return only Texts ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
IList<string> ChunkTexts(
string text
);
}
}
+38
View File
@@ -0,0 +1,38 @@
namespace xAiApi.Models
{
/// <summary>
/// Represents a Chunk of a Text which Produced by Text Chunker ...
/// </summary>
public class XTextChunk
{
/// <summary>
/// Zero Based Index of Chunk in Source Text ...
/// </summary>
public int Index { get; set; }
/// <summary>
/// Chunk Text Content ...
/// </summary>
public string Text { get; set; } = string.Empty;
/// <summary>
/// Source Name (e.g. File Name) which Chunk Extracted From ...
/// </summary>
public string Source { get; set; }
/// <summary>
/// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Start Offset of Chunk in Normalized Source Text ...
/// </summary>
public int StartOffset { get; set; }
/// <summary>
/// Length of Chunk Text ...
/// </summary>
public int Length => Text?.Length ?? 0;
}
}
+33
View File
@@ -0,0 +1,33 @@
namespace xAiApi.Models
{
/// <summary>
/// Text Chunker Descriptor ...
/// </summary>
public class XTextChunkerDescriptor
{
/// <summary>
/// Maximum Characters Count of each Chunk ...
/// </summary>
public int ChunkSize { get; set; } = 800;
/// <summary>
/// Characters Count which Shared between two Consecutive Chunks ...
/// </summary>
public int ChunkOverlap { get; set; } = 150;
/// <summary>
/// Chunks Smaller than this Size will be Merged into Previous Chunk ...
/// </summary>
public int MinChunkSize { get; set; } = 50;
/// <summary>
/// Chunck Identifier Separator ...
/// </summary>
public string ChunkIdentifierSeparator { get; set; } = "#";
/// <summary>
/// Normalize Line Endings and Repeated Whitespaces before Chunking ...
/// </summary>
public bool NormalizeWhitespace { get; set; } = true;
}
}
+588
View File
@@ -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
{
/// <summary>
/// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy:
/// Paragraphs -> Sentences -> Words -> Hard Cut ...
/// </summary>
public class XTextChunker : IXTextChunker
{
/// <summary>
/// Default Options which used when no Options Provided ...
/// </summary>
private readonly XAiApiConfiguration configuration;
/// <summary>
/// Matches Paragraph Boundaries (two or more Line Breaks) ...
/// </summary>
private static readonly Regex ParagraphSplitter = new(
@"\n\s*\n+",
RegexOptions.Compiled
);
/// <summary>
/// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ...
/// </summary>
private static readonly Regex SentenceSplitter = new(
@"(?<=[\.\!\?؟。!?])\s+|(?<=\n)",
RegexOptions.Compiled
);
/// <summary>
/// Matches Repeated Horizontal Whitespaces ...
/// </summary>
private static readonly Regex HorizontalWhitespace = new(
@"[ \t\f\v\u00A0]{2,}",
RegexOptions.Compiled
);
/// <summary>
/// Matches Three or more Line Breaks ...
/// </summary>
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;
}
/// <summary>
/// Split Text into Chunks ...
/// </summary>
/// <param name="text"></param>
/// <param name="source"></param>
/// <returns></returns>
public IList<XTextChunk> Chunk(
string text,
string source = null
)
{
//
var result = new List<XTextChunk>();
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;
}
/// <summary>
/// Split Text into Chunks and Return only Texts ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public IList<string> ChunkTexts(string text)
{
//
var result = Chunk(text, null)
.Select(c => c.Text)
.ToList();
//
return result;
}
//
#region Private ...
/// <summary>
/// Internal Text Unit with its Offset in Normalized Source ...
/// </summary>
private readonly struct Unit
{
public Unit(string text, int offset)
{
Text = text;
Offset = offset;
}
public string Text { get; }
public int Offset { get; }
}
/// <summary>
/// Normalize Line Endings and Whitespaces ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Create Chunk Model ...
/// </summary>
/// <param name="text"></param>
/// <param name="offset"></param>
/// <param name="index"></param>
/// <param name="source"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private List<Unit> BuildUnits(string text)
{
//
var result = new List<Unit>();
//
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;
}
/// <summary>
/// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ...
/// </summary>
/// <param name="text"></param>
/// <param name="splitter"></param>
/// <param name="baseOffset"></param>
/// <returns></returns>
private IEnumerable<Unit> 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;
}
}
}
/// <summary>
/// Trim Unit Text while Adjusting its Offset ...
/// </summary>
/// <param name="text"></param>
/// <param name="offset"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ...
/// </summary>
/// <param name="unit"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
private IEnumerable<Unit> 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++;
}
}
}
/// <summary>
/// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ...
/// </summary>
/// <param name="units"></param>
/// <returns></returns>
private List<Unit> Accumulate(List<Unit> units)
{
//
var result = new List<Unit>();
if (!units.HasChild())
{
return result;
}
//
var buffer = new StringBuilder();
var buffered = new List<Unit>();
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;
}
/// <summary>
/// Map Trailing Overlap Length of Buffered Units back to Source Offset ...
/// Units Joined by Single Space Separator in Buffer ...
/// </summary>
/// <param name="buffered"></param>
/// <param name="overlapLength"></param>
/// <returns></returns>
private int ComputeOverlapOffset(
List<Unit> 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;
}
/// <summary>
/// Take Trailing Overlap from Text, Aligned to Word Boundary ...
/// </summary>
/// <param name="text"></param>
/// <param name="overlap"></param>
/// <returns></returns>
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();
}
/// <summary>
/// Merge Chunks Smaller than MinChunkSize into their Predecessor ...
/// </summary>
/// <param name="chunks"></param>
/// <returns></returns>
private List<Unit> MergeSmallChunks(List<Unit> chunks)
{
//
if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2)
{
return chunks;
}
//
var result = new List<Unit>();
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;
}
/// <summary>
/// Characters Considered as Word Boundaries ...
/// </summary>
private readonly char[] WordBoundaries = [' ', '\n', '\t'];
#endregion
}
}
+6 -4
View File
@@ -190,10 +190,12 @@ namespace xAiApi
services.AddXAiFileContentExtractors();
//
// Register Default Ai Service ...
services.AddScoped<IXDefaultAiService, XDefaultAiService>();
services.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
services.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
// Register Text Chunker Service ...
services.AddXAiTextChunker();
//
// Register Default AI Services ...
services.AddXAiServices();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+8 -1
View File
@@ -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": "*"
}
}