Introduction
Local AI models are useful when an application needs to process documents without sending their content to an external service. Developers can run models on their own computers or servers and communicate with them through a local HTTP endpoint. This approach works well for document summarization, content analysis, information extraction, and internal knowledge tools.
However, processing large documents introduces a memory problem. Consider an application that needs to summarize a PDF converted into a text file containing several hundred megabytes of content. A straightforward implementation might read the complete file into a string and send it to the model in one request. This is easy to write, but it can consume a significant amount of memory and may exceed the model's context window.
A better approach is to read the document gradually, divide its content into manageable chunks, and send those chunks to the local model one at a time. The application only keeps a limited portion of the source document in memory while processing continues.
In this article, we will build a C# file-based application that reads a large text document using streams, divides it into smaller pieces, and sends each piece to a local Llama model through an OpenAI-compatible HTTP endpoint. We will also look at memory management, cancellation, error handling, and practical considerations for production applications.
Why Loading the Entire Document Is a Problem
A common approach to reading a document in C# is File.ReadAllText.
string document = await File.ReadAllTextAsync("large-document.txt");
This method is convenient for small files because it reads the complete content into memory and returns a string.
The problem becomes clear when the document is large. A 200 MB text file requires substantial memory for its string representation. Additional memory may be required when the application creates another string for the prompt, serializes the request into JSON, or stores the model response.
The model also has a context window limit. This limit determines how much input and generated content the model can handle in one request. Sending a document that exceeds this limit may result in an error, incomplete processing, or poor output.
There are two separate problems to solve:
- Application memory usage while reading and preparing the document.
- Model context limitations while sending content to the AI model.
Streaming solves the first problem by avoiding full-file loading. Chunking helps solve the second problem by limiting the amount of text included in each model request.
Understanding Streaming and Chunking
Streaming and chunking are related, but they solve different parts of the problem.
Streaming means reading data gradually instead of loading the complete file into memory. In .NET, FileStream and StreamReader provide APIs for reading file content incrementally.
Chunking means dividing the document into smaller sections that can be processed independently. Each section is sent to the model as a separate request.
For example, consider a document containing 100,000 lines. Instead of loading all lines into a single string, the application can read a fixed number of characters at a time and process each section.
The workflow looks like this:
- Open the document using a file stream.
- Read a limited amount of text into a buffer.
- Create a chunk from the available content.
- Send the chunk to the local AI model.
- Save the generated result.
- Release the processed chunk and continue reading.
- Repeat until the document reaches the end.
<text> </text>
<CodeBlock language="mermaid" editable> flowchart TD A[Large Document] --> B[Open File Stream] B --> C[Read Limited Buffer] C --> D[Create Text Chunk] D --> E[Send Chunk to Local AI Model] E --> F[Save Model Response] F --> G{More Content?} G -->|Yes| C G -->|No| H[Complete Processing] </CodeBlock>
This design keeps the amount of source text in memory under control. It also makes it easier to retry failed chunks without processing the entire document again.
Preparing the Local Llama Environment
For this example, we will use a local Llama server that exposes an OpenAI-compatible API.
The server should be running before starting the C# application. You also need to download a model that is suitable for your computer's available memory and processing capacity.
The example uses the following endpoint:
http://localhost:9931/v1/chat/completions
The model identifier must match the model exposed by your local server. You can check the available models through:
http://localhost:9931/v1/models
The exact endpoint and port depend on the local model runtime. If you use Ollama or another local server, configure the corresponding endpoint and request format.
Creating a C# File-Based Application
Create a file named LargeDocumentProcessor.cs.
A file-based application lets you run this utility without creating a traditional solution and project structure.
Start with the following package directive and namespace imports:
#!/usr/bin/env dotnet
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
This example uses HttpClient directly because the local server provides an HTTP-compatible chat endpoint. This keeps the implementation independent of a specific AI client library.
The application will use three main components:
- A document reader that produces bounded text chunks.
- An HTTP client that sends each chunk to the local model.
- A result writer that saves each response without keeping all results in memory.
Reading a Large Document in Bounded Chunks
The first important component is the document reader.
Instead of using File.ReadAllTextAsync, we will use StreamReader to read a limited number of characters at a time.
static async IAsyncEnumerable<string> ReadChunksAsync(
string filePath,
int chunkSize,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default)
{
using var reader = new StreamReader(filePath);
char[] buffer = new char[chunkSize];
int charactersRead;
while ((charactersRead = await reader.ReadAsync(
buffer.AsMemory(),
cancellationToken)) > 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return new string(buffer, 0, charactersRead);
}
}
The method uses IAsyncEnumerable so that the application can process each chunk asynchronously.
The buffer controls how much text is read during each iteration. For example, a chunk size of 12,000 characters means the reader requests at most that many characters for each chunk.
The method does not read the complete document before returning its first result. It reads the next portion only when the calling code requests another item.
This is important because the application can send one chunk to the model, save the response, and then continue reading the source file.
The example uses fixed-size character chunks. This keeps memory usage predictable, but it can split a sentence or paragraph between two chunks. For document analysis, paragraph-aware chunking is often better. We will discuss that improvement later.
Sending a Chunk to the Local AI Model
The next component sends a chunk to the local model.
The local server accepts a JSON request containing the model identifier, messages, and generation options.
static async Task<string> SendToLocalModelAsync(
HttpClient httpClient,
string endpoint,
string model,
string chunk,
CancellationToken cancellationToken)
{
var request = new
{
model,
stream = false,
messages = new[]
{
new
{
role = "system",
content =
"Summarize the supplied document section. " +
"Preserve important facts, names, figures, and decisions. " +
"Do not add information that is not present in the text."
},
new
{
role = "user",
content = chunk
}
}
};
using var response = await httpClient.PostAsJsonAsync(
endpoint,
request,
cancellationToken);
response.EnsureSuccessStatusCode();
await using var responseStream =
await response.Content.ReadAsStreamAsync(cancellationToken);
using var json = await JsonDocument.ParseAsync(
responseStream,
cancellationToken: cancellationToken);
return json.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString() ?? string.Empty;
}
The method creates a request containing the current chunk instead of the complete document.
The system message tells the model what kind of response is expected. In this example, the model summarizes the supplied section while preserving important information.
The request uses stream=false because we want to receive one completed summary for each chunk. This does not mean the source document is loaded entirely into memory. The input remains limited to the current chunk.
The response is read as a stream and parsed using JsonDocument. This avoids manually reading the complete response into a separate string before parsing it.
The response format shown here follows the OpenAI-compatible chat completions API. Other local model servers may return a different response structure, so adjust the parsing logic when using a different API.
Processing the Complete Document
Now we can connect the reader and model client.
The following implementation processes the document one chunk at a time and writes each summary directly to an output file.
var inputPath = args.Length > 0
? args[0]
: "large-document.txt";
var outputPath = "document-summary.txt";
var endpoint = Environment.GetEnvironmentVariable("LLAMA_ENDPOINT")
?? "http://localhost:9931/v1/chat/completions";
var model = Environment.GetEnvironmentVariable("LLAMA_MODEL")
?? "your-model-id";
if (!File.Exists(inputPath))
{
Console.WriteLine("Input document not found.");
return;
}
const int chunkSize = 12000;
using var cancellationSource = new CancellationTokenSource();
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromMinutes(5)
};
await using var output = new StreamWriter(
outputPath,
append: false,
Encoding.UTF8);
int chunkNumber = 0;
try
{
await foreach (var chunk in ReadChunksAsync(
inputPath,
chunkSize,
cancellationSource.Token))
{
chunkNumber++;
Console.WriteLine(
$"Processing chunk {chunkNumber}...");
string summary = await SendToLocalModelAsync(
httpClient,
endpoint,
model,
chunk,
cancellationSource.Token);
await output.WriteLineAsync(
$"--- Chunk {chunkNumber} ---");
await output.WriteLineAsync(summary);
await output.FlushAsync(
cancellationSource.Token);
}
Console.WriteLine(
$"Processing completed. Results saved to {outputPath}");
}
catch (HttpRequestException ex)
{
Console.WriteLine(
$"Unable to communicate with the local model: {ex.Message}");
}
catch (OperationCanceledException)
{
Console.WriteLine("Document processing was cancelled.");
}
The application opens the input file through the asynchronous chunk reader. It then sends each chunk to the model and writes the generated summary to the output file.
The important design decision is that the application does not store all summaries in a List or combine the complete source document into one large string. It writes each result as soon as it is received.
Flushing the output writer after each chunk also helps preserve completed results if a later request fails. For very large processing jobs, the application can additionally store chunk numbers and processing status in a database so that failed chunks can be retried.
Why Sequential Processing Is Useful
It may be tempting to send several chunks to the model simultaneously to reduce processing time. However, parallel processing increases resource usage.
Each request requires its own prompt, HTTP request data, and response processing. The local model also has to manage multiple requests. Depending on the model runtime and available hardware, too many simultaneous requests can reduce performance or cause memory pressure.
Sequential processing is a good starting point for large documents because it provides predictable resource usage.
| Processing approach | Memory usage | Processing behavior | Suitable scenario |
|---|
| Load entire document | High for large files | One large request | Small documents |
| Stream and process sequentially | Controlled | One request at a time | Large documents |
| Stream and process in parallel | Higher and variable | Multiple requests | Workloads with sufficient resources |
| Chunk and summarize in stages | Controlled | Multiple processing stages | Very large documents |
If parallel processing is necessary, use a bounded concurrency limit rather than creating a task for every chunk. This prevents the application from building an unbounded queue of requests.
Improving Chunk Quality
Fixed-size chunks are easy to implement, but they do not always preserve the meaning of a document.
For example, a paragraph may explain a business decision across several thousand characters. If the application splits that paragraph in the middle, the model may receive incomplete context.
A better approach is to create chunks around natural document boundaries, such as:
- Paragraphs.
- Headings and sections.
- Page boundaries.
- Sentence groups.
For text files, the application can read lines and accumulate them until a configured character limit is reached. It can then send the accumulated text as one chunk.
For PDFs, it is often better to extract text page by page and preserve headings and page references. This allows the application to maintain the original document structure while processing content in smaller sections.
Another useful technique is overlapping chunks. A small amount of text from the end of one chunk can be repeated at the beginning of the next chunk. This helps preserve context when an important sentence is split between two sections.
However, overlap increases the number of input tokens sent to the model. Keep it limited and use it only when the document structure requires it.
Handling Documents Larger Than the Model Context Window
Chunking reduces the size of each request, but it does not automatically create a complete summary of the original document.
Suppose a document contains 100 chunks. The model generates a summary for each chunk, but the application still needs to combine those summaries into a useful result.
One option is hierarchical summarization.
In this approach, the application first summarizes individual chunks. It then groups a limited number of those summaries and sends each group to the model for a higher-level summary. This process can continue until the application has a final result.
For example:
- Divide the source document into manageable chunks.
- Generate a summary for each chunk.
- Group the summaries into smaller batches.
- Summarize each batch.
- Repeat until the remaining summaries fit into one final request.
- Generate the final document summary.
This approach avoids sending the entire source document or all intermediate summaries in one request.
For applications that need exact information rather than summaries, a retrieval-based approach may be more appropriate. The application can store chunks with document identifiers, metadata, and embeddings, then retrieve only the relevant sections when a user asks a question.
Best Practices for Production Applications
Set chunk sizes based on token limits
A character limit is easy to implement, but models operate with tokens rather than characters. The number of tokens represented by a chunk depends on the language, formatting, and content.
Use a tokenizer compatible with the selected model when accurate token limits are important. Leave room for system instructions and the expected response.
Use cancellation tokens
Large documents may take a long time to process. Pass cancellation tokens to file operations and HTTP requests so that users can stop processing without waiting for every chunk to finish.
Save progress after each chunk
Do not wait until the entire document has been processed before saving results. Store completed summaries and their chunk numbers so that the application can resume after a failure.
Avoid unlimited parallel requests
Local model servers have limited hardware resources. Start with sequential processing and introduce bounded concurrency only after measuring the effect on memory and response time.
Keep source metadata
Store the document name, chunk number, page number, and section heading alongside each result. This makes it easier to trace a summary back to its original content.
Validate model output
AI-generated summaries can omit details or misunderstand the source. Validate important information before using it in business workflows. For financial, legal, and operational documents, keep the original source available for review.
Protect against prompt injection
Documents can contain instructions that attempt to influence the model. Treat document content as untrusted input. Make it clear in the system instructions that the document is data to analyze, not a source of instructions that can override the application's rules.
Common Mistakes to Avoid
One common mistake is replacing File.ReadAllText with a stream but still accumulating the entire document in a StringBuilder. This changes the reading API but does not solve the memory problem.
Another mistake is using extremely small chunks. Smaller chunks reduce the amount of input per request, but they increase the number of model calls and may remove useful context.
Developers should also avoid assuming that the character count is the same as the model's token count. A 12,000-character chunk can represent different token counts depending on the content.
Finally, do not store every request and response in memory until processing finishes. Write results incrementally and keep only the information required for the current processing step.
Advantages and Disadvantages
Advantages
- Processes large documents without loading the complete source file into memory.
- Keeps each model request within a manageable size.
- Works with local AI models without requiring a hosted AI service.
- Supports incremental output and recovery after processing failures.
- Allows different chunking strategies based on document structure.
- Can be extended with summarization, retrieval, and document indexing.
Disadvantages
- Processing many chunks requires multiple model requests.
- Sequential processing may take longer than carefully controlled parallel processing.
- Fixed-size chunks can separate related paragraphs or sentences.
- Summaries may lose details when information is repeatedly compressed.
- The application needs additional logic for retries, progress tracking, and error handling.
- Character-based chunk sizes do not guarantee that requests fit within the model's token limit.
Summary
Sending large documents to local AI models requires more than changing the file-reading method. The application must control how much content it reads, how much text it sends in each request, and how it stores the generated results.
Using StreamReader and IAsyncEnumerable allows a .NET application to read a document gradually. Dividing the content into manageable chunks helps keep model requests within the available context window. Writing each response directly to an output file avoids retaining all generated results in memory.
For larger document processing systems, these techniques can be extended with paragraph-aware chunking, hierarchical summarization, bounded parallel processing, and retrieval-based search.
The main principle is simple: process only the amount of document content needed for the current operation, save the result, and then move to the next section. This makes local AI document processing easier to manage and more suitable for applications that work with large files.
Join the conversation! Your thoughts help the community grow.