How to Implement Document Chunking for RAG in ASP.NET Core 10 Using C# – Fixed-Size, Recursive and Semantic Chunking (2026)

How to Implement Document Chunking for RAG in ASP.NET Core 10 Using C# – Fixed-Size, Recursive and Semantic Chunking (2026)

A support answer may depend on two neighboring sentences: one describes a deployment failure, and the next explains the fix. Split between them without enough context and retrieval may return an incomplete explanation. Put an entire manual into one vector and the same answer may be diluted by unrelated topics. Document chunking is the engineering decision between those extremes.

This tutorial implements document chunking for RAG in ASP.NET Core 10 using C#. It compares fixed-size, token-budget, recursive, sentence-aware and embedding-based semantic boundaries through one small API. The implementation preserves source slices, applies hard token limits and optionally generates final-chunk vectors through Microsoft.Extensions.AI.

What is document chunking in RAG?

Document chunking divides an extracted source into smaller retrieval units. Each unit should retain enough context to be useful, fit the chosen embedding model’s input budget and carry metadata that points back to the source. Chunking is not summarization: this example returns exact source substrings rather than rewriting the document.

Preserve source provenance through extraction, chunking and embedding. This tutorial returns storage-ready records; it does not claim to implement a vector database.
Preserve source provenance through extraction, chunking and embedding. This tutorial returns storage-ready records; it does not claim to implement a vector database. Original SVG diagram.

1. Why chunking matters for retrieval quality

An embedding represents the input it receives. A chunk containing several unrelated topics can make a relevant passage difficult to distinguish. A very short chunk can lose the subject, exception or condition that gives a sentence meaning. The useful unit depends on what questions users ask and how the source is structured.

Chunking also affects citation granularity, duplicated evidence, storage, embedding work and the context available to an answering model. Meeting an embedding input limit is necessary, but a chunk that fits is not automatically a good retrieval unit. Microsoft’s chunking guidance discusses both size and structure; its service-specific examples are background, not proof of an optimal size for this API.

Preprocess deliberately before chunking: establish reading order, remove repeated extraction artifacts when justified, preserve headings and record the extraction version. Do not change whitespace or normalize line endings after recording offsets. This API receives already extracted text and keeps offsets relative to that exact submitted string.

A sentence-level similarity heuristic is not a guarantee of coherent sections. The study Is Semantic Chunking Worth the Computational Cost? found that gains depend on the task and did not consistently justify the extra work in its experiments. That is a reason to evaluate a simple baseline, not a claim that semantic methods can never help.

2. Fixed-size, token, recursive, sentence and semantic chunking

StrategyBoundary signalPractical tradeoff
Fixed character windowMaximum UTF-16 length with token safety checksPredictable windows; can cut through concepts
Token-budget windowTokenizer count with a character safety ceilingMatches the declared encoding budget; may cut sentences
Recursive splittingParagraph, line, sentence-space and space separatorsUseful structural heuristic; not a Markdown parser
Sentence-aware packingPunctuation/paragraph units, then bounded packingKeeps simple units together; segmentation is heuristic
Semantic adjacent-unit splittingEmbedding similarity plus hard size checksExtra inference work; threshold needs evaluation
Compare chunking variants under the same model, retrieval settings, source version and question set. The diagram does not claim measured superiority.
Compare chunking variants under the same model, retrieval settings, source version and question set. The diagram does not claim measured superiority. Original SVG diagram.

The fixed and token modes share one safe window engine. Their budgets differ: fixed mode respects requested MaxChars, while token mode uses a 2,000-character safety ceiling and the requested MaxTokens as its primary bound. Both enforce both limits. Results can coincide when the same bound is active; different labels do not magically imply different boundaries.

Overlap is useful context with a duplication cost

This sample supports OverlapChars only for fixed mode and caps it at one quarter of MaxChars. It rounds the next start forward to a text-element boundary, so actual overlap can be smaller than requested. Token and structure-based modes require zero overlap, keeping their boundary behavior easy to compare.

Overlap preserves local context but duplicates content. UTF-16 source offsets are end-exclusive; the ASCII example makes their meaning easy to inspect.
Overlap preserves local context but duplicates content. UTF-16 source offsets are end-exclusive; the ASCII example makes their meaning easy to inspect. Original SVG diagram.

With an eight-character window and two-character overlap, ABCDEFGHIJKL produces ABCDEFGH and GHIJKL. The shared GH is intentional. Overlap increases repeated evidence and embedding work; it can cause several near-identical results to occupy a top-K list. Do not treat duplicate retrieved chunks as independent corroboration.

Do not append a new overlap-only chunk after the source ends. Ensure every iteration advances and reject invalid limits. Exact content hashes can help reuse embeddings, but repeated text at different source positions should retain its provenance rather than being silently deleted.

3. Create the .NET 10 project and configure dependencies

Project setup
dotnet new web -n Chunking.Api -f net10.0
cd Chunking.Api
dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.11.0
dotnet add package Microsoft.ML.Tokenizers --version 2.0.1
dotnet add package Microsoft.ML.Tokenizers.Data.Cl100kBase --version 2.0.1
dotnet add package PdfPig --version 0.1.16
Chunking.Api.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings><UserSecretsId>Chunking.Api.Local</UserSecretsId>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.11.0" />
    <PackageReference Include="Microsoft.ML.Tokenizers" Version="2.0.1" />
    <PackageReference Include="Microsoft.ML.Tokenizers.Data.Cl100kBase" Version="2.0.1" />
    <PackageReference Include="PdfPig" Version="0.1.16" />
  </ItemGroup>
</Project>

The packages are stable selections compatible with .NET 10. The OpenAI adapter brings the provider SDK and Microsoft.Extensions.AI types. The Cl100kBase data package supplies the tokenizer vocabulary locally. PdfPig is used only by the bounded extraction helper below. Review adapter dependencies, tokenizer compatibility, the encoding data package and PdfPig’s package listing before upgrading.

PDF extraction is a bounded worker helper; the HTTP API accepts text and declared source metadata. No unrestricted file-upload endpoint is exposed.
PDF extraction is a bounded worker helper; the HTTP API accepts text and declared source metadata. No unrestricted file-upload endpoint is exposed. Original SVG diagram.
appsettings.json
{
  "Demo": { "ApiKey": "" },
  "OpenAI": { "ApiKey": "" },
  "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } },
  "AllowedHosts": "localhost"
}
PowerShell: development secrets
dotnet user-secrets init
$demoKey = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
dotnet user-secrets set "Demo:ApiKey" $demoKey
# Required only for semantic mode or IncludeEmbeddings=true:
dotnet user-secrets set "OpenAI:ApiKey" "YOUR_PROVIDER_KEY"

Replace the provider placeholder privately. User Secrets avoids storing credentials in the repository but does not encrypt them. Use a managed secret store or controlled secret injection in production. The API key authenticating this local demonstration is different from the outbound provider key. Deterministic chunking does not send text to OpenAI.

The fixed provider is text-embedding-3-small with 512 requested dimensions. The selected model uses cl100k_base tokenization; do not substitute an Ollama or other provider model while retaining this tokenizer assumption. The OpenAI tokenizer cookbook explains model/encoding relationships. Verify both provider input limits and the encoding when changing models.

4. DTOs, token counting and source offsets

Contracts.cs
namespace Chunking.Api;
public sealed record ChunkOptions(int MaxChars = 400, int MaxTokens = 256,
    int OverlapChars = 0, double SimilarityThreshold = 0.75);
public sealed record ChunkRequest(string? DocumentId, string? Version, string? Text,
    string Strategy = "recursive", ChunkOptions? Options = null,
    string? SourceRef = null, string? HeadingPath = null, int? PageNumber = null,
    bool IncludeEmbeddings = false);
public readonly record struct TextRange(int Start, int End);
public sealed record DocumentChunk(string Id, string DocumentId, string Version, int Index,
    int StartUtf16, int EndUtf16, string Text, int Tokens, string ContentHash,
    string? SourceRef, string? HeadingPath, int? PageNumber, float[]? Embedding);
public sealed record ChunkResponse(string Strategy, string AlgorithmVersion, string Tokenizer,
    string? EmbeddingModel, int? Dimensions, DocumentChunk[] Chunks);
public sealed class ApiFailure(int status, string message) : Exception(message)
{ public int Status { get; } = status; }
public interface IChunker
{
    string Name { get; }
    Task<IReadOnlyList<TextRange>> SplitAsync(string text, ChunkOptions options, CancellationToken ct);
}

StartUtf16 is inclusive and EndUtf16 exclusive. Their unit is the .NET string’s UTF-16 code unit, not a Unicode scalar count, byte offset, token index or original PDF coordinate. The returned Text is always the submitted source slice at that range. The service rejects invalid UTF-16 rather than hashing a replacement-decoded approximation.

SourceRef, HeadingPath and PageNumber are supplied by the trusted extraction step and copied to chunks. The API does not invent page numbers or infer a heading hierarchy from arbitrary Markdown. For a section-aware pipeline, submit one structural section at a time with its declared heading path.

Token counts depend on encoding and input. Source offsets refer to the submitted string, not decoded token IDs or PDF byte positions.
Token counts depend on encoding and input. Source offsets refer to the submitted string, not decoded token IDs or PDF byte positions. Original SVG diagram.
RangeTools.cs
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.ML.Tokenizers;
namespace Chunking.Api;
public sealed class TokenBudget
{
    private readonly Tokenizer tokenizer = TiktokenTokenizer.CreateForEncoding("cl100k_base");
    private readonly object gate = new();
    public int Count(string text) { lock (gate) return tokenizer.CountTokens(text); }
}
public sealed class RangeTools(TokenBudget tokens)
{
    public bool Fits(string text, TextRange r, ChunkOptions o) =>
        r.End - r.Start <= o.MaxChars && tokens.Count(text[r.Start..r.End]) <= o.MaxTokens;
    // Conservative prefix search: stop at the first limit crossing; no monotonic BPE claim.
    public int FitEnd(string text, int start, int end, ChunkOptions o, CancellationToken ct)
    {
        var slice = text[start..end];
        var boundaries = StringInfo.ParseCombiningCharacters(slice).Skip(1).Append(slice.Length);
        var best = start;
        foreach (var b in boundaries)
        {
            ct.ThrowIfCancellationRequested();
            var candidate = new TextRange(start, start + b);
            if (!Fits(text, candidate, o)) break;
            best = candidate.End;
        }
        if (best == start) throw new ApiFailure(422, "One text element exceeds the configured limits.");
        return best;
    }
    public List<TextRange> Windows(string text, int start, int end, ChunkOptions o, CancellationToken ct)
    {
        var output = new List<TextRange>();
        while (start < end)
        {
            ct.ThrowIfCancellationRequested();
            var stop = FitEnd(text, start, end, o, ct);
            output.Add(new(start, stop));
            if (output.Count > 256) throw new ApiFailure(422, "Too many chunks; increase limits or split the source.");
            if (stop == end) break;
            // Choose a text-element boundary at/after the requested overlap start.
            var target = Math.Max(start + 1, stop - o.OverlapChars);
            var next = StringInfo.ParseCombiningCharacters(text)
                .Append(text.Length).First(b => b >= target);
            start = Math.Min(next, stop); // always advances, never creates a gap
        }
        return output;
    }
    public List<TextRange> SentenceUnits(string text, ChunkOptions o, CancellationToken ct)
    {
        var units = new List<TextRange>(); var start = 0;
        foreach (Match m in Regex.Matches(text, @"[.!?](?:\s+|$)|\n{2,}", RegexOptions.CultureInvariant))
        {
            var end = m.Index + m.Length;
            if (end > start) units.AddRange(Windows(text, start, end, o with { OverlapChars = 0 }, ct));
            start = end;
        }
        if (start < text.Length) units.AddRange(Windows(text, start, text.Length, o with { OverlapChars = 0 }, ct));
        if (units.Count > 128) throw new ApiFailure(422, "Too many sentence units for this bounded demo.");
        return units;
    }
    public List<TextRange> Pack(string text, IReadOnlyList<TextRange> units, ChunkOptions o, CancellationToken ct)
    {
        var result = new List<TextRange>();
        foreach (var unit in units)
        {
            ct.ThrowIfCancellationRequested();
            if (result.Count > 0 && Fits(text, new(result[^1].Start, unit.End), o))
                result[^1] = new(result[^1].Start, unit.End);
            else result.Add(unit);
        }
        return result;
    }
}

Microsoft.ML.Tokenizers CountTokens counts the candidate text under cl100k_base. Token counts are not a fixed ratio of characters: punctuation, languages, code and whitespace change the mapping. The sample reuses one tokenizer and serializes access for a conservative threading boundary. See Microsoft’s tokenizer guide.

FitEnd checks text-element boundaries and stops at the first budget crossing. It is deliberately conservative: BPE token counts are not assumed to increase monotonically with every added character, and the code does not claim to find the globally longest fitting prefix. A text element that cannot fit either budget produces 422 instead of a non-progressing loop.

This readable prefix-check implementation repeatedly tokenizes substrings and is not optimized for bulk ingestion. It is bounded by the API’s 12,000-unit source limit. A production implementation can use tokenizer index APIs with careful normalization/offset handling, then verify final source slices and token counts. Do not decode arbitrary token slices and assume their character offsets match the original source.

5. Complete fixed, token-budget, recursive and sentence chunkers

DeterministicChunkers.cs
namespace Chunking.Api;
public sealed class FixedChunker(RangeTools tools) : IChunker
{
    public string Name => "fixed";
    public Task<IReadOnlyList<TextRange>> SplitAsync(string t, ChunkOptions o, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<TextRange>>(tools.Windows(t, 0, t.Length, o, ct));
}
public sealed class TokenChunker(RangeTools tools) : IChunker
{
    public string Name => "token";
    public Task<IReadOnlyList<TextRange>> SplitAsync(string t, ChunkOptions o, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<TextRange>>(tools.Windows(t, 0, t.Length, o, ct));
}
public sealed class SentenceChunker(RangeTools tools) : IChunker
{
    public string Name => "sentence";
    public Task<IReadOnlyList<TextRange>> SplitAsync(string t, ChunkOptions o, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<TextRange>>(tools.Pack(t, tools.SentenceUnits(t, o, ct), o, ct));
}
public sealed class RecursiveChunker(RangeTools tools) : IChunker
{
    public string Name => "recursive";
    private static readonly string[] Separators = ["\n\n", "\n", ". ", " "];
    public Task<IReadOnlyList<TextRange>> SplitAsync(string t, ChunkOptions o, CancellationToken ct)
    {
        var leaves = new List<TextRange>();
        void Split(TextRange r, int level)
        {
            ct.ThrowIfCancellationRequested();
            if (tools.Fits(t, r, o)) { leaves.Add(r); return; }
            if (level == Separators.Length)
            { leaves.AddRange(tools.Windows(t, r.Start, r.End, o, ct)); return; }
            var separator = Separators[level]; var start = r.Start;
            var position = t.IndexOf(separator, start, r.End - start, StringComparison.Ordinal);
            if (position < 0) { Split(r, level + 1); return; }
            while (position >= 0)
            {
                var end = position + separator.Length;
                Split(new(start, end), level + 1); start = end;
                position = start < r.End ? t.IndexOf(separator, start, r.End - start, StringComparison.Ordinal) : -1;
            }
            if (start < r.End) Split(new(start, r.End), level + 1);
        }
        Split(new(0, t.Length), 0);
        return Task.FromResult<IReadOnlyList<TextRange>>(tools.Pack(t, leaves, o, ct));
    }
}
Each range is accepted if it fits, otherwise split at successively finer separators. At the last level a bounded text-element fallback guarantees progress; the completed leaves are then packed.
Each range is accepted if it fits, otherwise split at successively finer separators. At the last level a bounded text-element fallback guarantees progress; the completed leaves are then packed. Original SVG diagram.

Recursive mode first accepts ranges that fit. Oversized ranges are split through paragraph, line, dot-space and space separators, with a bounded text-element fallback at the last level. Separators stay inside ranges, so the output points to actual source substrings. The final pack step merges adjacent leaves only when both limits permit it.

This is a separator hierarchy, not a full document parser. Markdown code fences, tables, lists and headings can still be split. A paragraph that fits can contain several sentences, and a long unbroken line eventually becomes bounded windows. There is no claim that every recursive result corresponds to a semantic section.

Abbreviations, decimals, code and languages without these punctuation conventions need stronger segmentation. The sample states the heuristic instead of claiming perfect sentence detection.
Abbreviations, decimals, code and languages without these punctuation conventions need stronger segmentation. The sample states the heuristic instead of claiming perfect sentence detection. Original SVG diagram.

Sentence mode uses a deliberately visible punctuation/paragraph heuristic. It does not correctly resolve every abbreviation, decimal, quoted sentence or language-specific boundary. Oversized sentence-like units are split before packing, and a 128-unit cap bounds work. For higher-quality segmentation, use a language-aware sentence detector and preserve its offsets.

For comparison, Semantic Kernel provides TextChunker helpers with configurable token counters. The official TextChunker usage sample is useful background. This tutorial implements its own explicit range contract rather than implying those helpers preserve the same offsets or algorithm choices.

6. Semantic chunking with Microsoft.Extensions.AI

The semantic strategy embeds bounded sentence-like units, compares each unit with its predecessor and starts a new chunk when cosine similarity is below the configured threshold. A hard size limit can also force a boundary. It compares adjacent units, not each sentence with the centroid of the entire growing chunk.

EmbeddingGateway.cs
using Microsoft.Extensions.AI;
using OpenAI;
namespace Chunking.Api;
public sealed class EmbeddingGateway(IConfiguration config) : IDisposable
{
    public const string Model = "text-embedding-3-small";
    public const int Dimensions = 512;
    private readonly Lazy<IEmbeddingGenerator<string, Embedding<float>>> generator = new(() =>
    {
        var key = config["OpenAI:ApiKey"];
        if (string.IsNullOrWhiteSpace(key)) throw new ApiFailure(503, "Configure the embedding provider key.");
        return new OpenAIClient(key).GetEmbeddingClient(Model).AsIEmbeddingGenerator();
    });
    public async Task<float[][]> GenerateAsync(string[] texts, CancellationToken ct)
    {
        var output = new List<float[]>();
        for (var start = 0; start < texts.Length; start += 16)
        {
            ct.ThrowIfCancellationRequested();
            using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
            budget.CancelAfter(TimeSpan.FromSeconds(30));
            var batch = texts.Skip(start).Take(16).ToArray();
            try
            {
                var result = await generator.Value.GenerateAsync(batch,
                    new EmbeddingGenerationOptions { Dimensions = Dimensions }, budget.Token);
                if (result.Count != batch.Length) throw new ApiFailure(502, "Embedding count mismatch.");
                foreach (var embedding in result)
                {
                    var vector = embedding.Vector.ToArray();
                    if (vector.Length != Dimensions) throw new ApiFailure(502, "Embedding dimension mismatch.");
                    try { _ = VectorMath.Cosine(vector, vector); }
                    catch (ArgumentException) { throw new ApiFailure(502, "Invalid embedding vector."); }
                    output.Add(vector);
                }
            }
            catch (OperationCanceledException) when (!ct.IsCancellationRequested)
            { throw new ApiFailure(504, "Embedding batch exceeded its time budget."); }
        }
        return output.ToArray();
    }
    public void Dispose() { if (generator.IsValueCreated) generator.Value.Dispose(); }
}

The gateway uses IEmbeddingGenerator<string, Embedding<float>> through the stable OpenAI adapter. It sends at most 16 inputs per batch and verifies result count, dimensions and usable vector values. The lazy provider is not created for ordinary deterministic requests. A missing provider key produces a safe error when embedding work is requested.

The provider abstraction does not remove model-specific constraints or data handling. All sentence units sent for semantic analysis leave the application for the configured OpenAI service. Review the IEmbeddingGenerator contract, adapter API and provider embedding documentation.

VectorMath.cs
namespace Chunking.Api;

public static class VectorMath
{
    public static double Cosine(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
    {
        if (a.Length == 0 || a.Length != b.Length)
            throw new ArgumentException("Vectors must be non-empty and have equal dimensions.");
        double dot = 0, normA = 0, normB = 0;
        for (var i = 0; i < a.Length; i++)
        {
            if (!float.IsFinite(a[i]) || !float.IsFinite(b[i]))
                throw new ArgumentException("Vector coordinates must be finite.");
            dot += (double)a[i] * b[i];
            normA += (double)a[i] * a[i];
            normB += (double)b[i] * b[i];
        }
        if (normA == 0 || normB == 0)
            throw new ArgumentException("Cosine is undefined for a zero vector.");
        return Math.Clamp(dot / (Math.Sqrt(normA) * Math.Sqrt(normB)), -1.0, 1.0);
    }
}
SemanticChunker.cs
namespace Chunking.Api;
public sealed class SemanticChunker(RangeTools tools, EmbeddingGateway embeddings) : IChunker
{
    public string Name => "semantic";
    public async Task<IReadOnlyList<TextRange>> SplitAsync(string text, ChunkOptions o, CancellationToken ct)
    {
        var units = tools.SentenceUnits(text, o, ct)
            .Where(r => !string.IsNullOrWhiteSpace(text[r.Start..r.End])).ToArray();
        if (units.Length == 0) return [];
        var vectors = await embeddings.GenerateAsync(units.Select(r => text[r.Start..r.End]).ToArray(), ct);
        var output = new List<TextRange>(); var start = units[0].Start;
        for (var i = 1; i < units.Length; i++)
        {
            ct.ThrowIfCancellationRequested();
            var similarity = VectorMath.Cosine(vectors[i - 1], vectors[i]);
            var merged = new TextRange(start, units[i].End);
            if (similarity < o.SimilarityThreshold || !tools.Fits(text, merged, o))
            { output.Add(new(start, units[i - 1].End)); start = units[i].Start; }
        }
        output.Add(new(start, units[^1].End));
        return output;
    }
}
A low adjacent similarity or a hard size limit creates a new chunk. Semantic boundaries remain model- and corpus-dependent; provider failure is never disguised as a successful semantic result.
A low adjacent similarity or a hard size limit creates a new chunk. Semantic boundaries remain model- and corpus-dependent; provider failure is never disguised as a successful semantic result. Original SVG diagram.

For nonzero vectors, cosine is the dot product divided by the product of the vector lengths. The code rejects unequal dimensions, zero vectors and non-finite coordinates. As a toy calculation, (1,0) and (1,1) have cosine 1/sqrt(2), approximately 0.70710678. That arithmetic was checked independently in Python; it is not an observed sentence similarity.

A threshold of 0.75 is only an example. With the implemented “below threshold” rule, equality does not trigger a semantic boundary. Raising the threshold generally makes a semantic break easier to trigger, but hard caps and sentence segmentation also affect final chunks. A cosine value is not a percentage of shared meaning.

Semantic mode can still produce poor boundaries when adjacent sentences share vocabulary across a topic shift or use different wording within one topic. It also drops whitespace-only units before embedding; those units contain no retrieval content. Any remaining chunk text is an exact range of the input, not a concatenation of rewritten sentences.

7. Preserve metadata and optionally embed the final chunks

ChunkService.cs
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace Chunking.Api;
public sealed class ChunkService(IEnumerable<IChunker> chunkers, TokenBudget tokens,
    RangeTools tools, EmbeddingGateway embeddings)
{
    private static string Hash(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
    public async Task<ChunkResponse> RunAsync(ChunkRequest request, CancellationToken ct)
    {
        static string Required(string? s, int max, string name) =>
            !string.IsNullOrWhiteSpace(s) && s.Length <= max ? s : throw new ApiFailure(400, $"Invalid {name}.");
        var docId = Required(request.DocumentId, 100, "document ID");
        var version = Required(request.Version, 100, "version");
        var text = Required(request.Text, 12000, "text (maximum 12,000 UTF-16 units)");
        for (var i = 0; i < text.Length; i++)
        {
            if (!char.IsSurrogate(text[i])) continue;
            if (i + 1 >= text.Length || !char.IsSurrogatePair(text[i], text[i + 1]))
                throw new ApiFailure(400, "Text must contain valid UTF-16.");
            i++;
        }
        if (request.SourceRef?.Length > 256 || request.HeadingPath?.Length > 256
            || request.PageNumber is < 1 or > 100000)
            throw new ApiFailure(400, "Invalid source metadata.");
        var strategy = request.Strategy?.ToLowerInvariant() ?? "";
        var selected = chunkers.SingleOrDefault(c => c.Name == strategy)
            ?? throw new ApiFailure(400, "Use fixed, token, recursive, sentence or semantic.");
        var options = request.Options ?? new ChunkOptions();
        // Token mode uses a 2,000-character safety ceiling; MaxTokens is its primary budget.
        if (strategy == "token") options = options with { MaxChars = 2000 };
        if (options.MaxChars is < 8 or > 2000 || options.MaxTokens is < 8 or > 512
            || options.OverlapChars < 0 || options.OverlapChars > options.MaxChars / 4
            || !double.IsFinite(options.SimilarityThreshold)
            || options.SimilarityThreshold is < -1 or > 1)
            throw new ApiFailure(400, "Invalid chunk limits, overlap or cosine threshold.");
        if (strategy is not "fixed" && options.OverlapChars != 0)
            throw new ApiFailure(400, "OverlapChars is supported only by fixed mode in this demo.");
        var ranges = await selected.SplitAsync(text, options, ct);
        if (ranges.Count > 256) throw new ApiFailure(422, "Too many output chunks.");
        var chunkTexts = ranges.Select(r => text[r.Start..r.End]).ToArray();
        for (var i = 0; i < ranges.Count; i++)
            if (!tools.Fits(text, ranges[i], options)) throw new ApiFailure(500, "Chunk postcondition failed.");
        if (request.IncludeEmbeddings && chunkTexts.Any(string.IsNullOrWhiteSpace))
            throw new ApiFailure(422, "Whitespace-only chunks cannot be embedded; revise boundaries.");
        var vectors = request.IncludeEmbeddings
            ? await embeddings.GenerateAsync(chunkTexts, ct) : null;
        var fingerprint = JsonSerializer.Serialize(new { docId, version, strategy, options,
            sourceHash = Hash(text), request.SourceRef, request.HeadingPath, request.PageNumber,
            algorithm = "chunk-v1" });
        var chunks = ranges.Select((r, i) => new DocumentChunk(
            Hash(fingerprint + ":" + r.Start + ":" + r.End), docId, version, i,
            r.Start, r.End, chunkTexts[i], tokens.Count(chunkTexts[i]), Hash(chunkTexts[i]),
            request.SourceRef, request.HeadingPath, request.PageNumber, vectors?[i])).ToArray();
        return new(strategy, "chunk-v1", "cl100k_base",
            strategy == "semantic" || request.IncludeEmbeddings ? EmbeddingGateway.Model : null,
            strategy == "semantic" || request.IncludeEmbeddings ? EmbeddingGateway.Dimensions : null, chunks);
    }
}
Sentence vectors used to choose boundaries are not reused as final chunk vectors. Store the embedding configuration and source permissions with each persisted record.
Sentence vectors used to choose boundaries are not reused as final chunk vectors. Store the embedding configuration and source permissions with each persisted record. Original SVG diagram.

The response includes a source ID/version, ordered chunk index, source range, token count and content hash. The deterministic ID includes the source hash, declared strategy/options, source metadata, algorithm version and range. Repeating the same declared input/configuration produces the same ID; a new source version or boundary configuration changes the fingerprint.

This does not make semantic inference perfectly reproducible forever. Provider model behavior can change, and the simple ID does not include a provider artifact digest. Persist the provider model/dimensions, tokenizer/package version and corpus release metadata in your storage layer. Bump the algorithm/configuration version when a model or segmentation release changes.

IncludeEmbeddings=true generates one new vector per final chunk. The sentence vectors used to choose semantic boundaries are not averaged or reused as the final chunk vectors: a merged chunk is a different input. The response’s model/dimension fields indicate embedding work; in semantic mode with IncludeEmbeddings=false, no final vectors are returned even though unit embeddings were used internally.

Whitespace-only fixed chunks are allowed as source slices, but optional embedding rejects them with 422 rather than losing input/output alignment. Choose larger windows or handle extraction whitespace deliberately. Exact content hashes can support embedding-cache reuse while separate chunk IDs retain source positions.

Preparing for vector storage means adding tenant/document permissions, source URI policy, model-space identity, update/delete rules and an idempotent upsert operation. This tutorial returns data; it does not persist vectors or claim a configured database index. Keep cache keys scoped by model, dimensions, preprocessing and allowed data access, not text hash alone.

8. Plain text, Markdown, PDF extraction and OCR limitations

Plain text is the most direct input: the supplied string is the offset reference. For Markdown, a trusted ingestion stage should identify headings, fenced code, tables and lists with an appropriate parser, then submit meaningful sections with HeadingPath. This example does not infer a Markdown AST or promise that a recursive separator preserves code blocks.

For PDFs, extract one page at a time and carry its page number into the chunk request. The helper below uses PdfPig’s documented ContentOrderTextExtractor. It is a worker-side utility, not an unrestricted HTTP upload endpoint.

PdfPages.cs
using UglyToad.PdfPig;
using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor;
namespace Chunking.Api;
public sealed record ExtractedPage(int PageNumber, string Text);
public static class PdfPages
{
    // Invoke from a trusted ingestion worker, not an unrestricted HTTP upload route.
    public static IReadOnlyList<ExtractedPage> Extract(byte[] bytes, CancellationToken ct)
    {
        if (bytes.Length is 0 or > 10 * 1024 * 1024) throw new ApiFailure(400, "PDF size limit exceeded.");
        using var pdf = PdfDocument.Open(bytes);
        if (pdf.NumberOfPages > 100) throw new ApiFailure(422, "PDF page limit exceeded.");
        var pages = new List<ExtractedPage>();
        foreach (var page in pdf.GetPages())
        {
            ct.ThrowIfCancellationRequested();
            var text = ContentOrderTextExtractor.GetText(page);
            if (string.IsNullOrWhiteSpace(text))
                throw new ApiFailure(422, "A page has no extracted text; review OCR requirements.");
            if (text.Length > 12000) throw new ApiFailure(422, "Extracted page needs bounded structural segmentation.");
            pages.Add(new(page.Number, text));
        }
        return pages;
    }
}
Worker-side usage sketch
// bytes comes from an authorized, size-limited document source.
foreach (var page in PdfPages.Extract(bytes, cancellationToken))
{
    var request = new ChunkRequest(
        DocumentId: "manual-42",
        Version: "2026-11",
        Text: page.Text,
        Strategy: "recursive",
        SourceRef: "manual-42.pdf",
        HeadingPath: null,
        PageNumber: page.PageNumber);
    var response = await chunkService.RunAsync(request, cancellationToken);
    // Persist response.Chunks using your authorized ingestion/storage policy.
}

The sketch assumes bytes, cancellationToken and chunkService are supplied by your ingestion worker. It is not another Program.cs file. Each page’s offsets refer to that page’s extracted text, not the original PDF byte positions or a concatenated multi-page document.

PdfPig reads embedded PDF text; it does not perform OCR for a scanned page. An empty extraction needs review: it may be a scan, an intentionally blank page or another extraction problem. Multi-column order, headers/footers, tables, ligatures and layout can require additional analysis. The official repository and extractor source explain its scope.

The helper caps bytes/pages and rejects oversized extracted pages instead of silently truncating them. Parsing is synchronous and cancellation is checked between pages, so a difficult page is not instantly interruptible. Untrusted document parsing belongs in a constrained worker with time/resource isolation, file validation and malware handling appropriate to your environment.

9. Complete Program.cs and centralized error handling

ApiErrorHandler.cs
using Microsoft.AspNetCore.Diagnostics;
using System.ClientModel;

namespace Chunking.Api;

public sealed class ApiErrorHandler(ILogger<ApiErrorHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception error, CancellationToken ct)
    {
        if (http.RequestAborted.IsCancellationRequested) return true;
        var status = error switch
        {
            ApiFailure safe => safe.Status,
            BadHttpRequestException => 400,
            ClientResultException provider when provider.Status == 429 => 503,
            ClientResultException or HttpRequestException => 502,
            _ => 500
        };
        logger.LogWarning("Embedding request failed: {Type}, status {Status}, trace {TraceId}",
            error.GetType().Name, status, http.TraceIdentifier);
        if (status == 503) http.Response.Headers.RetryAfter = "1";
        http.Response.Headers.CacheControl = "no-store";
        await Results.Problem(statusCode: status,
            title: status >= 500 ? "Embedding operation unavailable." : "Request rejected.",
            detail: error is ApiFailure known ? known.Message : null,
            extensions: new Dictionary<string, object?> { ["traceId"] = http.TraceIdentifier })
            .ExecuteAsync(http);
        return true;
    }
}
Program.cs
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.RateLimiting;
using Chunking.Api;
var builder = WebApplication.CreateBuilder(args);
var demoKey = builder.Configuration["Demo:ApiKey"];
if (string.IsNullOrWhiteSpace(demoKey) || demoKey.Length is < 32 or > 256)
    throw new InvalidOperationException("Configure a random Demo:ApiKey of 32–256 characters.");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024);
builder.Services.AddSingleton<TokenBudget>();
builder.Services.AddSingleton<RangeTools>();
builder.Services.AddSingleton<EmbeddingGateway>();
builder.Services.AddScoped<IChunker, FixedChunker>();
builder.Services.AddScoped<IChunker, TokenChunker>();
builder.Services.AddScoped<IChunker, RecursiveChunker>();
builder.Services.AddScoped<IChunker, SentenceChunker>();
builder.Services.AddScoped<IChunker, SemanticChunker>();
builder.Services.AddScoped<ChunkService>();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<ApiErrorHandler>();
builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);
builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = 429;
    o.AddConcurrencyLimiter("chunking", p => { p.PermitLimit = 2; p.QueueLimit = 0; });
});
var expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(demoKey));
var app = builder.Build();
app.UseExceptionHandler();
app.UseRouting();
app.Use(async (http, next) =>
{
    http.Response.Headers.CacheControl = "no-store";
    if (!http.Request.Headers.TryGetValue("X-Demo-Key", out var key) || key.Count != 1
        || key.ToString().Length > 256 || !CryptographicOperations.FixedTimeEquals(expectedHash,
            SHA256.HashData(Encoding.UTF8.GetBytes(key.ToString()))))
    { http.Response.StatusCode = 401; return; }
    await next(http);
});
app.UseRateLimiter();
app.MapPost("/api/chunks", (ChunkRequest request, ChunkService service, CancellationToken ct)
    => service.RunAsync(request, ct)).RequireRateLimiting("chunking");
app.Run();

POST /api/chunks validates a demonstration key, limits the request body and attaches a two-request per-process concurrency limiter. The service bounds source size, output count and sentence units. This is a teaching API, not a complete production authentication or distributed admission-control system.

The error handler returns safe status/detail/trace information rather than raw provider exceptions or request text. In .NET 10, handled exceptions can suppress built-in diagnostics; the explicit structured warning makes failures visible. No provider vectors, source text or keys are logged by the tutorial code.

Related ASP.NET PB foundations: OpenAI API integration, global exception handling and JWT authentication. Use proper identity and document authorization before accepting sensitive or multi-tenant ingestion.

10. Test chunk boundaries with Postman and deterministic checks

PowerShell: build and start
dotnet restore --use-lock-file
dotnet build --no-restore
$env:ASPNETCORE_ENVIRONMENT = "Development"
dotnet run --no-launch-profile -- --urls "http://localhost:5095"

Create a private Postman variable demoKey from setup. Send Content-Type: application/json and X-Demo-Key: {{demoKey}} to POST http://localhost:5095/api/chunks. The local HTTP address is for development; protect production ingress with HTTPS.

A fixed-window example with inspectable boundaries

Fixed-size request
{
  "documentId": "ascii-demo",
  "version": "v1",
  "text": "ABCDEFGHIJKL",
  "strategy": "fixed",
  "options": {
    "maxChars": 8,
    "maxTokens": 256,
    "overlapChars": 2,
    "similarityThreshold": 0.75
  },
  "sourceRef": "example.txt",
  "includeEmbeddings": false
}

The expected text/range pairs are below; the character bound is active and the token budget is ample for this toy ASCII input. These window calculations were checked in Python, not by executing the API:

IndexStartUtf16EndUtf16Text
008ABCDEFGH
1612GHIJKL

A successful response is HTTP 200 with strategy, algorithmVersion, tokenizer, embeddingModel, dimensions and chunks. For this deterministic request without vectors, embeddingModel/dimensions are null. Each chunk also carries a calculated ID/hash, token count and source metadata. No invented token count or hash is presented as captured output.

Compare strategies on the same source

Representative document request
{
  "documentId": "hosting-notes",
  "version": "2026-11",
  "text": "# Hosting

Publish the API to IIS. Install the hosting components before verifying startup.

# Security

Keep credentials outside source control. Restrict access to protected endpoints.",
  "strategy": "recursive",
  "options": {
    "maxChars": 100,
    "maxTokens": 64,
    "overlapChars": 0,
    "similarityThreshold": 0.75
  },
  "sourceRef": "hosting-notes.md",
  "headingPath": null,
  "includeEmbeddings": false
}

Repeat with fixed, token, sentence and semantic. For token mode, MaxChars is replaced by its 2,000-character safety ceiling; inspect the effective behavior rather than assuming the request’s 100-character value still controls it. For semantic mode, configure the provider key; do not assert exact boundaries until you run that provider configuration.

Set IncludeEmbeddings=true to generate final chunk vectors. Verify one vector per chunk with 512 coordinates. In semantic mode this adds final-chunk embedding work after sentence-unit embedding work. Counts, latency and provider usage should be observed locally rather than copied from a fabricated screenshot.

Check invariants before judging relevance

Standalone deterministic check: separate .NET 10 console project
// Copy Contracts.cs, RangeTools.cs and DeterministicChunkers.cs into this test project.
// Add Microsoft.ML.Tokenizers and Data.Cl100kBase 2.0.1.
using Chunking.Api;
var budget = new TokenBudget();
var tools = new RangeTools(budget);
var options = new ChunkOptions(MaxChars: 8, MaxTokens: 256, OverlapChars: 2);
var fixedResult = await new FixedChunker(tools).SplitAsync("ABCDEFGHIJKL", options, default);
if (!fixedResult.SequenceEqual(new[] { new TextRange(0, 8), new TextRange(6, 12) }))
    throw new Exception("Unexpected overlap boundaries.");
var source = "Alpha beta.\n\nGamma delta. Emoji: 😀 end.";
var noOverlap = new ChunkOptions(MaxChars: 16, MaxTokens: 16);
var ranges = await new RecursiveChunker(tools).SplitAsync(source, noOverlap, default);
if (string.Concat(ranges.Select(r => source[r.Start..r.End])) != source)
    throw new Exception("Source coverage failed.");
if (ranges.Any(r => r.Start >= r.End || !tools.Fits(source, r, noOverlap)))
    throw new Exception("A chunk violates its limits.");

This is provided test code, not an executed C# result. Add Unicode combining sequences, very long unbroken strings, blank paragraphs, Markdown fences and cancellation tests. For API-level checks, repeat the same request and compare IDs, then change the version or limits and inspect the new IDs.

Negative caseExpected behavior
No/incorrect demo key401
Blank source, invalid UTF-16 or text above 12,000 UTF-16 units400
Unknown strategy or malformed/unknown JSON properties400
MaxTokens outside 8–512 or invalid cosine threshold400
Overlap requested outside fixed mode400
One text element exceeds limits or too many chunks/units422
Whitespace-only final chunk with vectors requested422
Missing provider key when embedding is needed503
Provider rejects request or returns unusable vectorsSafe provider error, commonly 502
Embedding batch exceeds its budget504 unless caller already cancelled
Per-process concurrency capacity exceeded429

A disconnected caller may receive no JSON error body. Deterministic loops check cancellation during work; PDF parsing checks it between pages. Provider failures never cause this implementation to silently label fixed chunks as semantic chunks.

11. Evaluate chunking with representative questions and evidence

Start with questions users actually ask and label the supporting evidence spans in the original source. Keep extraction, source versions, embedding model, vector index, query set and retrieval settings fixed while changing chunking parameters. Otherwise a change in retrieval can be mistakenly attributed to boundaries.

Chunk identities change across strategies, so a relevance set based only on old chunk IDs is not a fair comparison. Map results back to document/page/source ranges and define when a returned chunk contains sufficient evidence. A substring overlap by itself may not mean the chunk supports the answer; review the evidence criterion explicitly.

MeasureDefinition / purpose
Precision@KRelevant retrieved units in the first K divided by K; underfilled slots count as non-relevant under this declared convention
Recall@KJudged relevant evidence units retrieved in the first K divided by all judged relevant units for that question
MRR@KAverage reciprocal rank of the first relevant result, with zero if none appears within K
Evidence coverageWhether the retrieved ranges contain the complete supporting passage rather than a fragment
Duplicate-context rateHow much overlapping or repeated context occupies the result/prompt budget
Operational costObserved ingestion time, embedding usage, memory and storage under the tested setup

If two of the first four returned results are relevant and there are three judged relevant evidence units, Precision@4=2/4 and Recall@4=2/3. These are hypothetical arithmetic examples, not measured scores for the implementation. For queries with no relevant evidence, recall has a zero denominator; define a separate no-answer evaluation instead of silently assigning perfect recall.

Use an evidence-based labeling policy that does not reward overlap duplicates as separate successes. You can measure both chunk-level relevance and unique source/evidence coverage, but label them separately. A high chunk-level precision with repeated copies of one passage can still waste the answering model’s context.

Try a small declared experiment matrix: fixed windows with zero/modest overlap, recursive mode, sentence mode and semantic mode at several thresholds, under equivalent final token budgets where possible. Record actual chunk token distributions because a character cap may bind first. Use a held-out question set when reporting comparisons.

Keep the semantic threshold separate from retrieval similarity thresholds: one decides ingestion boundaries; another might decide query-result acceptance. A chunking method that appears coherent to a reader is not automatically best for retrieval or answer faithfulness. No universal optimum, benchmark gain or traffic benefit is claimed.

12. Large documents, memory, performance and security

Bound synchronous work and move bulk ingestion to workers

The API is a bounded teaching service: up to 12,000 source UTF-16 units, 256 final chunks and 128 sentence-like units. It holds source slices and vectors in memory, and its readable prefix search repeatedly tokenizes candidates. Do not expose it as an unbounded multi-gigabyte document endpoint or call it a streaming parser.

For bulk work, extract structural units incrementally, put jobs in a durable queue, checkpoint source/version progress and batch embeddings within provider limits. Avoid holding a database transaction while calling a model. Write idempotent chunk upserts and remove obsolete chunks when the source version changes.

Semantic chunking adds unit embeddings and optional final-chunk embeddings. Cache only under a reviewed model/preprocessing/data-scope key, measure cold/warm behavior and avoid stacking retries across SDK, application and infrastructure without a plan. A timeout/cancellation does not guarantee no provider-side processing or billing occurred.

Keep metadata accurate rather than convenient

Do not prepend a heading to Text after calculating offsets and still claim Text is an exact source slice. Store a separate embedding input if you add heading context, count that full input against the model budget and version the preprocessing contract. Likewise, OCR normalization and PDF reading-order changes need their own extraction versions.

Preserve parent document permissions in every stored chunk. Metadata is not an authorization decision. A client-supplied SourceRef should be treated as a label unless validated by the ingestion system; this API does not fetch it, preventing a caller-controlled download/SSRF path.

Protect sensitive ingestion

  • Replace the shared demo key with verified identity and document-specific authorization.
  • Use HTTPS, controlled secret injection, per-tenant budgets and distributed admission controls as required.
  • Review whether sending source text to the selected embedding provider is permitted.
  • Keep source text, vectors and credentials out of normal logs and screenshots.
  • Apply retention/deletion rules to source copies, chunk vectors, caches and backups.
  • Run untrusted PDF/OCR processing in constrained workers and review file-type/resource limits.
  • Keep content and permissions separate from any future agent/tool instructions.

A well-chunked malicious document remains untrusted content. If you later use chunks in RAG, protect the generation/tool layer against prompt injection and enforce source access before retrieval. Chunking itself does not provide those safeguards.

13. Troubleshooting and frequently asked questions

ProblemWhat to inspect
Chunks exceed provider input limitsVerify the encoding/model pairing and count the actual embedding input, including any added heading or prefix.
Token mode ignores requested MaxCharsBy design it uses a 2,000-character safety ceiling; MaxTokens is its primary budget. Fixed mode uses requested MaxChars.
Fixed and token results look identicalThe same hard bound can be active in both window modes. Inspect token/character distributions instead of expecting different text by label.
Recursive mode splits code or a tableIt is a separator heuristic, not a Markdown AST parser. Pre-segment structural elements upstream.
Semantic mode produces too many short chunksReview sentence segmentation, threshold direction, hard caps and model space; do not tune only the threshold.
Semantic chunk looks too long despite similar sentencesEvery merged range must fit both caps; lower MaxTokens/MaxChars if your downstream context requires it.
Whitespace-only final chunks cannot be embeddedRevise windows or preprocessing deliberately; the service refuses to silently drop them and misalign vectors.
Repeated chunks occupy top-K resultsInspect overlap and exact/near-duplicate handling at retrieval time; preserve provenance even if vectors are reused.
Citation points to wrong charactersConfirm offsets refer to the exact submitted string/page and no later normalization or heading prefix changed it.
PDF text is empty or out of orderReview scan/OCR requirements, blank pages and layout/reading order. Extraction is not OCR.
Tokenizer data cannot be loadedRestore the matching Cl100kBase data package and use the declared encoding name.
Semantic request returns provider errorsCheck the separate provider key, account/model access, token limits and batch response validation.
C# API result differs from a toy illustrationThe toy window calculation is deterministic arithmetic; sentence/provider behavior needs actual execution and evaluation.

Which chunking strategy is best for RAG?

There is no universal best strategy. Start with a bounded fixed or recursive baseline, then compare evidence retrieval, context duplication and operational cost on your documents and questions.

Are characters, words and tokens interchangeable?

No. This API records UTF-16 source offsets, keeps text-element-safe hard windows and counts cl100k_base tokens. A word or character ratio is not an exact token budget.

Does semantic chunking guarantee topic boundaries?

No. This implementation uses adjacent-unit cosine similarity plus size checks. Its sentence detector and threshold are heuristics, and different model/configuration choices can change boundaries.

Should I always use overlap?

No. It can preserve context across hard boundaries, but duplicates storage, embedding work and retrieved evidence. Evaluate it; this tutorial deliberately limits overlap to fixed mode.

Can I use a local model instead of OpenAI?

Yes, after changing the provider adapter, tokenizer, input limits and model-space metadata together. An OpenAI cl100k_base counter should not be presented as exact for an unrelated local tokenizer.

Are sentence vectors valid final chunk vectors?

Not automatically. This sample generates final-chunk embeddings separately when requested. Averaging constituent vectors is a different design and is not implemented or claimed equivalent.

Does PdfPig extract scanned PDFs?

It can read embedded PDF text, but scanned image pages need OCR. Layout, tables and reading order may require additional analysis even when text is embedded.

Are headings automatically preserved?

The API preserves declared HeadingPath metadata, not an inferred hierarchy. Extract headings/sections upstream and keep any contextual embedding prefix separate from the exact source slice.

Does the article include a vector database?

No. It prepares chunk records and optional vectors for a separate storage pipeline. Upserts, authorization filters, indexes and deletion semantics belong in that integration.

What was actually tested?

The ASCII window ranges and a toy cosine value were checked independently in Python. The C# build, PDF parser, tokenizer runtime, API and provider calls were not executed here. The draft includes local checks and negative cases so these limitations are explicit.

14. Conclusion: choose boundaries you can inspect and evaluate

Reliable chunking combines three responsibilities: enforce the model budget, preserve useful evidence and retain a trustworthy path back to the source. This tutorial makes those responsibilities visible through exact slices, declared tokenization, bounded strategies and metadata-rich results.

Run the deterministic checks first, inspect real sentence and PDF extraction behavior, then evaluate retrieval using source-level evidence judgments. Add semantic boundaries only when their measured benefit justifies their extra work for your use case. Keep source, algorithm and model versions together when releasing an ingestion pipeline.

Possible supporting tutorials

  • Validating source-span citations after OCR corrections.
  • Keeping Markdown tables and code fences atomic during RAG ingestion.
  • Comparing sentence-boundary detectors on .NET technical documentation.

These are future ideas only; no additional posts were created.

15. References and research notes

Research date: 4 November 2026. Stable NuGet listings determine the selected package versions; some API-reference documentation views carry broader prerelease notices. Re-check the package/API contracts when upgrading.

Research and search-intent review focused on developer questions about character versus token counts, overlap loops, sentence/PDF extraction, metadata loss and the cost of semantic boundaries. Microsoft guidance and the Semantic Kernel sample provide useful comparison points; this article adds an explicit source-range contract, bounded implementations, a shared API and failure checks. No keyword-volume, difficulty, ranking or performance numbers are invented.

Comments