
Series - AI chat applications with .NET: Part 1: A Console Chat with IChatClient · Part 2: Chat with Local Data
The console chat from the first part can follow a conversation, but it has no access to the services, incidents or costs of a team. Giving it local data is the next step, and for a small data set the implementation can be straightforward: read the files and include their contents in the request.
This approach is usually called context stuffing. Here, seven JSON files become part of the system prompt and travel with every question. It avoids a separate search system and makes the experiment easy to inspect: the application knows exactly which records it intended to send. The following examples use the same operations data for lookups, comparisons and aggregations, then examine where the approach becomes unreliable or expensive. The local runs also expose a less obvious problem: a request can succeed even when the configured context window is too small to retain all of its data.
Versions and data: Same stack as part 1 - .NET 10, Microsoft.Extensions.AI 10.11.0, OllamaSharp 5.5.0. The sample data is fictional. The console output was captured with
llama3.2andqwen2.5:7bin a local Ollama instance. Token counts forgpt-4.1-miniwere computed with its tokenizer, not measured in Azure.
The sample data
The chat answers questions about the operations of a fictional software platform team. Seven JSON files, 32 KB in total:
| File | Content |
|---|---|
services.json | 12 services with owner team, runtime, hosting, SLA target and monthly availability in 2026 |
incidents.json | 31 production incidents with severity, duration, root cause and postmortem status |
cloud-costs.json | Monthly Azure cost per service in euros |
teams.json | 5 teams with lead, engineers, open positions and on-call rotation |
runtimes.json | Runtimes in use with their end-of-support date |
deployments.json | Deployments, change failure rate and lead time per service and quarter |
projects.json | Roadmap projects with budget, spending, status and main risk |
Each file starts with a description that explains what it contains. The entries themselves are plain JSON, here shortened to two of ten months:
1{
2 "id": "svc-payment",
3 "name": "Payment Gateway",
4 "team": "Commerce",
5 "runtime": ".NET 8",
6 "hosting": "Azure Kubernetes Service",
7 "tier": "critical",
8 "slaTargetPercent": 99.95,
9 "availabilityPercentByMonth": {
10 "2026-01": 99.974,
11 "2026-10": 99.91
12 }
13}The files are part of the project and copied next to the executable:
1<ItemGroup>
2 <None Update="data\*.json" CopyToOutputDirectory="PreserveNewest" />
3</ItemGroup>Data into the system prompt
Loading is ordinary file I/O. The order is fixed, so the prompt is identical on every start - which matters later for caching:
1IReadOnlyList<DataFile> files = Directory.GetFiles(directory, "*.json")
2 .Order(StringComparer.OrdinalIgnoreCase)
3 .Select(path => new DataFile(Path.GetFileName(path), File.ReadAllText(path)))
4 .ToList();The system prompt consists of the instructions followed by every file, each under its own heading:
1StringBuilder prompt = new(instructions.Trim());
2prompt.AppendLine().AppendLine();
3prompt.AppendLine("# Data");
4
5foreach (DataFile file in files)
6{
7 prompt.AppendLine();
8 prompt.AppendLine($"## File: {file.Name}");
9 prompt.AppendLine("```json");
10 prompt.AppendLine(file.Content.Trim());
11 prompt.AppendLine("```");
12}The heading gives each file a label, and the code fence makes the request easier to inspect. These delimiters do not create a security boundary. Placing data in a system message is suitable only for controlled content in this example; externally supplied documents should remain clearly separated from trusted instructions, and permissions must be enforced before retrieval or prompt assembly.
The instructions come from appsettings.json. Each sentence has a job:
1You are the operations assistant of a software platform team.
2Answer questions only from the data below.
3If the answer is not in the data, say so and do not guess.
4Quote numbers exactly as they appear in the data, including unit and period.
5Answer clearly and concisely.The second sentence limits the scope. The third gives the model explicit permission to say “I don’t know” - without it, a model tends to fill gaps with plausible inventions. The fourth targets the most common error with numbers: rounding, dropping the unit or mixing up the period.
The chat loop from part 1 does not change. The only difference is the first entry in the history:
List<ChatMessage> history = [new(ChatRole.System, systemPrompt)];Two options for every request
A low temperature reduces sampling variation, although it does not make factual answers reliable. Part 1 introduced ChatOptions; now they are passed with every request:
1ChatOptions chatOptions = new() { Temperature = 0.1f };
2
3if (provider == "Ollama")
4{
5 chatOptions.AddOllamaOption(OllamaOption.NumCtx, 16384);
6}
7
8await foreach (ChatResponseUpdate update in chatClient.GetStreamingResponseAsync(history, chatOptions, token))
9{
10 // ...
11}The second option is the important one. num_ctx sets the context window Ollama loads the model with. AddOllamaOption comes from OllamaSharp and stores the value in the provider-neutral ChatOptions. Microsoft Foundry needs nothing comparable: gpt-4.1-mini has a context window of about one million tokens.
When the data does not fit
With llama3.2, the system prompt is 10,623 tokens long. The local instance used here allocated 4,096 tokens by default. Current Ollama context defaults
depend on available VRAM and configuration, so that value should not be assumed on another machine. The same chat without num_ctx:
17 files, 33,044 characters in the system prompt.
2System prompt with data: 2,050 tokens.
3Model llama3.2 loaded, context window 4,096 tokens.Ollama read 2,050 of 10,623 tokens. There was no exception, no warning and no error in the response. Only the end of the prompt survived - the last services of services.json and the teams. The answers show what the model saw:
1You: How many SEV1 incidents were there in 2026?
2AI: Unfortunately, the provided data does not contain information about SEV1 incidents. The data only
3 includes information about Service Level Agreements (SLAs) and availability percentages for various
4 services, as well as team information and on-call rotations.
5
6You: Which services run on a runtime whose support ends in 2026?
7AI: [...] Note that the support end dates for these runtimes are not explicitly stated in the provided
8 data, but based on the general knowledge of runtime support, we can infer that these runtimes are no
9 longer supported as of 2026.The instructions at the beginning of the prompt were cut off as well. “Do not guess” no longer existed, and the model guessed: it answered from general knowledge, multiplied availability percentages to calculate “cloud costs” and, asked about budgets, wrote a Python script with invented budget values.
In this run, truncation did not produce a request error. The successful response therefore concealed the more consequential failure: the model was answering without much of the intended data or the instructions that preceded it.
The warm-up request: load, count, cache
Part 1 loaded the model with an empty generate request. With data in the prompt, a better warm-up is a real chat request that contains the system prompt and allows a single output token:
1ChatOptions warmUpOptions = chatOptions.Clone();
2warmUpOptions.MaxOutputTokens = 1;
3
4ChatResponse response = await chatClient.GetResponseAsync(history, warmUpOptions);
5long? systemPromptTokens = response.Usage?.InputTokenCount;The request warms the model with the same options used for real questions. It also exposes usage information and can make the shared prompt prefix available for reuse.
Because the warm-up includes num_ctx, Ollama prepares the model with the intended 16,384-token allocation. Warming a different configuration can require another load when the first real question arrives, which would defeat much of the benefit.
The reported input usage helps diagnose what Ollama processed. It includes the serialized chat prompt and is not an independent count of the intended file contents. Comparing it with the prompt length catches the extreme discrepancy in this example:
1// A heuristic for this English/JSON sample, not a tokenizer or proof of truncation.
2if (systemPromptTokens < systemPrompt.Length / 6)
3{
4 throw new InvalidOperationException(
5 $"Only {systemPromptTokens:N0} tokens of the system prompt reached the model. Increase the context window.");
6}The complete sample averages about 3.1 characters per token, so 2,050 reported tokens are suspicious for this particular prompt. Character ratios vary by tokenizer, language and content; reliable budgeting needs an appropriate tokenizer, space for the answer and checks against the configured context limit.
The stable data prefix can also be reused. Ollama retains computed prompt state while the relevant cache is available; placing the unchanged files before the appended conversation gives later requests a common prefix. The measured effect with llama3.2 on the test machine was substantial:
| Without warm-up | With warm-up | |
|---|---|---|
| First question: reading 10,645 input tokens | 1,756 ms | 17 ms |
| First question: time to first token | 4,083 ms | 41 ms |
| Second question: reading 10,686 input tokens | 17 ms | 17 ms |
Without the warm-up, the first question pays for reloading the model with the larger context and for reading all data. The warm-up moves that work to startup; it does not remove the latency or guarantee that a later request will reuse the cache.
For Microsoft Foundry, the probe request from part 1 now sends the system prompt instead of “Hello”. It still validates endpoint, key and deployment, and it additionally reports the token count of the data and may establish a reusable prompt prefix, subject to the cache behavior described below.
Lookups work
With the data in place and a 16,384-token window, llama3.2 answers questions that need one place in the data:
1You: Which team owns the Payment Gateway, and who leads that team?
2AI: The Payment Gateway is owned by the "Commerce" team. The lead of the Commerce team is Mara Lindqvist.
3 [10,645 in · read in 20 ms · 25 out · first token 46 ms · 371 ms]
4
5You: Which runtime does it run on?
6AI: The Payment Gateway runs on .NET 8.
7 [10,686 in · read in 18 ms · 11 out · first token 41 ms · 173 ms]The first answer combines two files: the owner from services.json, the lead from teams.json. The follow-up works through the history, exactly as in part 1. And every question sends more than 10,600 input tokens for a 25-token answer.
| Question | Correct answer | llama3.2 |
|---|---|---|
| Which team owns the Payment Gateway, and who leads that team? | Commerce, Mara Lindqvist | correct |
| Which runtime does it run on? (follow-up) | .NET 8 | correct |
| What was the root cause of INC-2026-129? | Unbounded retry loop amplified a partial outage | correct |
| What is the average salary in the Commerce team? | Not in the data | “I don’t have the data to determine the average salary” |
| Who is on call for the Platform team in calendar week 50? | Amara Okafor | Ines Duarte - the engineer of week 48 |
The salary answer is the instruction “say so and do not guess” at work. The on-call answer is the first warning sign: a lookup in a small object with eight keys, and the model picked a neighboring entry.
Aggregations do not
Questions that need many places in the data - filter, count, compare, sum - fail. The same five questions with llama3.2 (3.2B parameters) and the larger qwen2.5:7b:
| Question | Correct answer | llama3.2 | qwen2.5:7b |
|---|---|---|---|
| Which services missed their SLA target in October 2026? | Payment Gateway, Search API, Notification Service | 9 services, including 6 that met their target | 5 services, Search API missing |
| How many SEV1 incidents were there in 2026? | 4 | “I don’t have the information” | 3, one with an ID that does not exist |
| What were the total cloud costs of all services in September 2026? | 64,730 EUR | 64,210 | 64,100 |
| Which services run on a runtime whose support ends in 2026? | 5 services | 3 of 5 | 2 of 5 |
| Which projects are over budget? | PRJ-11, PRJ-14, PRJ-18 | 2 of 3 | 1 of 3 |
The cost answer of llama3.2 is the most instructive one. It listed all twelve values correctly and then added them up wrong:
1Total cloud costs in September 2026 = 6410 + 9320 + 3990 + 11500 + 9940 + 2840 + 1360 + 4710 + 5430
2 + 4820 + 970 + 3440 = 64,210A second run with the same data in compact JSON produced different wrong answers: 114,220 for the same sum, and the correct count of four SEV1 incidents - backed by a list in which two of the four incidents were actually SEV2 incidents and a third had the wrong date. A correct number with wrong evidence is worse than a wrong number, because it passes a quick check.
These failures are consistent with how the application uses the model: it generates text from a prompt rather than executing a query over the JSON. For “how many SEV1 incidents in 2026” it has to attend to 31 records spread over thousands of tokens, apply two conditions and count - while generating text token by token. A lookup needs one place in the data; an aggregation needs all of them, and a sum over twelve numbers needs arithmetic that the model only approximates. Other models may perform better, but this local comparison does not measure them. The application can avoid the dependence on model arithmetic by calculating the same aggregates in code.
The format of the data matters
The data is read by a model, not by a parser. A few decisions make that easier and cheaper.
Field names should make units explicit. costEur, budgetThousandEur, durationMinutes and slaTargetPercent put the unit right next to the number. The instruction to quote numbers with their unit only works if the unit is there. Values in thousands ("spentThousandEur": 205) also mean fewer digits to copy than 205000.
The representation also affects how much input each request carries. The first version of the sample data stored monthly values as arrays of { "month": ..., "availabilityPercent": ... } objects - 48 KB. The same values as month-keyed objects ("2026-10": 99.91) take 32 KB. Every byte saved is saved on every request.
Whitespace improves readability during development, but it can add input tokens. The application can keep the source files formatted and serialize compact JSON while assembling the prompt:
1using JsonDocument document = JsonDocument.Parse(file.Content);
2string compact = JsonSerializer.Serialize(document.RootElement);| System prompt | Characters | llama3.2 tokens | gpt-4.1-mini tokens |
|---|---|---|---|
| Pretty-printed JSON | 33,044 | 10,623 | 10,567 |
| Minified JSON | 22,562 | 7,317 | 7,280 |
31 % fewer tokens, with the same answers to the lookup questions. It does not fix the aggregations - they were wrong in both runs.
Descriptions supply conventions that field names cannot express on their own. In incidents.json, stating that SEV1 is the most severe level makes that ordering part of the context rather than leaving it to the model’s assumptions.
What it costs
With Ollama, the price is hardware. A 16,384-token context window needs considerably more memory than the default. A model that no longer fits into the GPU memory runs partly on the CPU and gets much slower. ollama ps shows how a loaded model is split.
With Microsoft Foundry, the price is per token, and context stuffing changes the bill completely. In part 1, the input grew with the conversation. Now every request starts with more than 10,000 tokens before the first question is even asked.
Token counts for OpenAI models can be computed locally with Microsoft.ML.Tokenizers
and the Microsoft.ML.Tokenizers.Data.O200kBase package:
1TiktokenTokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-4.1-mini");
2int tokens = tokenizer.CountTokens(systemPrompt); // 10,567With example prices of 0.40 US dollars per million input tokens for gpt-4.1-mini, the data alone costs about 0.0042 dollars per question - about 4.20 dollars per 1,000 questions, before the question, the history and the answer.
Prompt caching can reduce that recurring cost. Foundry caches the processed beginning of a prompt automatically and bills cached input tokens at a discount. For gpt-4.1-mini and other models before the GPT-5.6 family, the rules
are:
- the prompt must be at least 1,024 tokens long, and the first 1,024 tokens must be identical;
- beyond that, cache hits count in steps of 128 tokens;
- the cache is usually cleared after 5 to 10 minutes of inactivity and always within an hour.
A system prompt with stable data at the very beginning is the ideal case. Microsoft.Extensions.AI reports the cached part of the input in UsageDetails, so the cost calculation from part 1 only needs one more price:
1long cachedInputTokens = usage.CachedInputTokenCount ?? 0;
2long uncachedInputTokens = inputTokens - cachedInputTokens;
3
4decimal cost = (uncachedInputTokens * pricing.InputPerMillionTokens
5 + cachedInputTokens * pricing.CachedInputPerMillionTokens
6 + outputTokens * pricing.OutputPerMillionTokens) / 1_000_000m;With a cached price of 0.10 dollars per million tokens, the data costs about 0.0011 dollars per question instead of 0.0042. A startup probe incurs its own token cost and may help subsequent requests reuse the prefix. The reported cached token count, rather than the probe alone, confirms whether a later request benefited.
Three rules keep the cache effective: stable content first, dynamic content last; never put a timestamp or a request ID into the system prompt; and keep the file order deterministic. A single changed character in the first 1,024 tokens means a cache miss. For newer model families (GPT-5.6 and later), Foundry adds cache breakpoints and can charge for cache writes - the documentation describes the details.
Rate limits are the other cost. Every question consumes more than 10,000 tokens of the deployment’s tokens-per-minute quota, so HTTP 429 arrives much sooner than with the short prompts of part 1.
When context stuffing is the right tool
Context stuffing is useful for a bounded, relatively stable data set when questions mostly concern individual records or explanations. It keeps a prototype small and makes all intended context available without first tuning retrieval. Enough room must remain for the question, conversation and output; fitting the files alone is insufficient.
As the data grows, the cost of sending it repeatedly and the risk of losing important details become harder to justify. Retrieval can narrow the context when each question needs a different subset. Questions about exact counts, filters and totals call for another change: code or a database query should compute the result, regardless of how much text fits in the prompt.
What the model really sees
The examples show that access to all records is useful but insufficient. The application has to ensure that the intended records reach the model, and the model can still select the wrong field or perform an incorrect calculation afterwards.
For a small operations assistant, context stuffing is a practical baseline against which more elaborate designs can be measured. Token budgeting and controlled data preparation make that baseline meaningful. Exact aggregations remain a separate responsibility, which later parts move into tools.
Further reading
Related articles

- 15 min read
A Console Chat with IChatClient: Ollama and Microsoft Foundry
Series - AI chat applications with .NET: Part 1: A Console Chat with IChatClient. The following parts build on this chat step by step.

- 10 min read
Migrating Semantic Kernel Agents to Microsoft Agent Framework
Microsoft Agent Framework is the successor to the agent capabilities in Semantic Kernel and AutoGen. That statement is easy to misread as …

- 22 min read
Building Production MCP Servers with ASP.NET Core
An MCP server can look deceptively small. A package is installed, a method receives an attribute and ASP.NET Core maps an endpoint. That is …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
