
Series - AI chat applications with .NET: Part 1: A Console Chat with IChatClient · Part 2: Chat with Local Data · Part 3: RAG in Memory
The second part sent more than 10,600 tokens of operations data with every question. Several lookups worked, but calculations and comparisons remained unreliable, and the entire data set had to fit into the model’s context window.
Retrieval-augmented generation (RAG) reduces the amount of data sent with each question. The application first searches for relevant records, then includes those records in the model request. This introduces a separate retrieval step whose quality can be examined independently of the generated answer.
For this example, the vectors stay in memory. The same fictional data and questions from part 2 make it possible to compare both approaches without introducing a database or search service. The comparison shows why retrieval helps with some lookups, why it struggles with identifiers, and why retrieving a handful of similar records is insufficient for a question about every record.
Versions and data: Same stack and fictional sample data as part 2, plus
embeddinggemmaas embedding model in Ollama. The console output was captured withllama3.2in a local Ollama instance. Token counts fortext-embedding-3-smallandgpt-4.1-miniwere computed with their tokenizers, not measured in Azure.
Three steps, two phases
RAG has an indexing phase at startup and three steps per question:
1At startup For every question
2
3data/*.json question (+ previous question)
4 │ chunking │ embedding
5 ▼ ▼
688 chunks query vector
7 │ embedding │ cosine similarity to every chunk
8 ▼ ▼
988 vectors in memory ──────────────────▶ top 5 chunks + question ──▶ chat model ──▶ answer
10 (retrieval) (augmentation) (generation)Retrieval ranks chunks against the query vector. Augmentation adds the selected text to the request, and generation uses the chat client from part 1 to produce an answer. Separating the steps makes it possible to test whether the right records were found before evaluating the model’s wording.
A second abstraction: IEmbeddingGenerator
An embedding model maps text to a numerical vector. It is trained so that related texts tend to occupy nearby positions, although similarity does not establish that one text answers a question or supports a claim. Microsoft.Extensions.AI provides IEmbeddingGenerator<TInput, TEmbedding> for this, the counterpart to IChatClient.
With Ollama, the same client class implements both interfaces. A second instance points to the embedding model:
1IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator =
2 new OllamaApiClient(new Uri(settings.Endpoint), "embeddinggemma");With Microsoft Foundry, the OpenAIClient from part 1 provides an embedding client for an embedding deployment:
1IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator =
2 openAi.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator();embeddinggemma (Ollama) | text-embedding-3-small (Foundry) | |
|---|---|---|
| Runs | Locally, about 620 MB | In Azure, as a separate deployment |
| Dimensions | 768 | 1,536 |
| Input limit | 2,048 tokens | 8,192 tokens |
| Cost | Own hardware | Per input token, a fraction of chat model prices |
The input limit matters for chunking: a chunk longer than the embedding model can read is not represented completely by its vector.
Chunking: what is a searchable unit?
The search does not compare the question with files, but with chunks. Their size and content decide what can be found.
The sample data consists of seven JSON files, each with one main list - services, incidents, teams, costs. One entry of that list is a natural unit: one incident, one service, one project. Every chunk additionally gets the file name and the description of its file:
1foreach (JsonObject entry in entries.Cast<JsonObject>())
2{
3 StringBuilder text = new();
4 text.AppendLine($"File: {file}");
5 text.AppendLine($"Description: {description}");
6 text.Append(entry.ToJsonString());
7
8 yield return new DataChunk(file, LabelOf(entry), text.ToString());
9}A chunk then looks like this:
1File: incidents.json
2Description: Fictional sample data for a blog article. All names, numbers and events are invented.
3Production incidents from November 2025 to October 2026. SEV1 is the most severe level.
4{"id":"INC-2026-129","date":"2026-10-14","serviceId":"svc-payment","severity":"SEV1","durationMinutes":129,"rootCause":"Unbounded retry loop amplified a partial outage","postmortemDone":false}The description is not decoration. Without it, an isolated incident would lose the information that SEV1 is the most severe level, and an isolated cost entry would lose its currency. Every chunk has to stand on its own, because it will reach the model alone.
The seven files produce 88 chunks of about 125 tokens each. The repeated descriptions make all chunks together larger than the whole data set in part 2 - irrelevant, because only five of them travel with a question.
Indexing: one request for all chunks
All chunks are embedded in a single call at startup:
1GeneratedEmbeddings<Embedding<float>> embeddings = await embeddingGenerator.GenerateAsync(
2 chunks.Select(c => c.Text), cancellationToken: cancellationToken);
3
4for (int i = 0; i < chunks.Count; i++)
5{
6 _entries.Add((chunks[i], embeddings[i].Vector));
7}On the test machine, embeddinggemma needed about 3 to 5 seconds for 13,758 tokens. The result is 88 vectors with 768 dimensions: 88 × 768 × 4 bytes, about 264 KiB. At this size, “in memory” is not a compromise but the obvious choice.
The index lives as long as the process. Every start embeds everything again - without a per-token bill in local Ollama, or with billed embedding input in Foundry. That is fine for 88 chunks and the main reason for a persistent vector store at larger volumes.
Search: cosine similarity
For every question, the question itself becomes a vector and is compared with all chunks:
1ReadOnlyMemory<float> queryVector = await embeddingGenerator.GenerateVectorAsync(query, cancellationToken: cancellationToken);
2
3return _entries
4 .Select(e => new SearchResult(e.Chunk, TensorPrimitives.CosineSimilarity(queryVector.Span, e.Vector.Span)))
5 .OrderByDescending(r => r.Score)
6 .Take(top)
7 .ToList();Cosine similarity ranges from -1 to 1 for nonzero vectors: 1 means the same direction, 0 means orthogonal, and -1 means opposite directions. The semantic interpretation depends on the embedding model; a score of zero is not a general test for unrelated text. TensorPrimitives from System.Numerics.Tensors provides an optimized implementation. A direct package reference keeps that dependency explicit even if it is already available transitively.
The search is a linear scan over all 88 vectors and takes far less time than embedding the question. For millions of vectors, a vector database replaces the scan with an approximate index. The principle stays the same.
Augmentation: data for this request only
The chat loop from part 1 changes in one place. The found chunks are added to the request, but not to the history:
1string? previousQuestion = history.LastOrDefault(m => m.Role == ChatRole.User)?.Text;
2string searchText = previousQuestion is null ? input : $"{previousQuestion}\n{input}";
3IReadOnlyList<SearchResult> sources = await index.SearchAsync(searchText, top: 5);
4
5List<ChatMessage> request = [.. history, new ChatMessage(ChatRole.User, RagPrompt.Build(input, sources))];
6
7// ... stream the answer for request ...
8
9history.Add(new ChatMessage(ChatRole.User, input));
10history.AddMessages(updates);The request construction separates the conversation from the evidence retrieved for the current question.
Only the original question and generated answer enter the conversation history. The retrieved chunks are temporary input for this request, which avoids retaining hundreds of tokens of old evidence per turn. Earlier answers can still contain outdated facts, so this reduces one source of stale context rather than eliminating it.
Follow-up questions also need retrieval context. On its own, “Which runtime does it run on?” does not identify the service. On its own, it finds all eight runtimes and two unrelated services - but not the Payment Gateway that “it” refers to. Together with the previous question, the Payment Gateway is the best hit with a similarity of 0.46. Rewriting the follow-up into a complete question with an extra model call is the more robust, more expensive alternative.
The system prompt describes how to use the supplied evidence. It says “Each question comes with the data that was found for it. Answer only from this data.” - followed by the same rules as in part 2: say when something is missing, quote numbers exactly.
The user message for the model looks like this:
1Data found for this question:
2
3---
4File: teams.json
5Description: ...
6{"name":"Platform","lead":"Aylin Kaya", ... }
7
8---
9...
10
11Question: Who is on call for the Platform team in calendar week 50?Lookups: same answers, a tenth of the tokens
The same questions as in part 2, with llama3.2, an 8,192-token context window and the top 5 chunks per question:
1You: Who is on call for the Platform team in calendar week 50?
2 sources: 0.37 teams.json › Platform · Aylin Kaya | 0.33 teams.json › Discovery · Tomás Herrera | ...
3AI: According to the data, in calendar week 50, the on-call person for the Platform team is Amara Okafor.
4 [844 in · read in 85 ms · 27 out · first token 106 ms · 309 ms]| Question | Correct answer | Part 2: all data | Part 3: RAG, top 5 | Input tokens |
|---|---|---|---|---|
| Which team owns the Payment Gateway, and who leads that team? | Commerce, Mara Lindqvist | correct | correct | 868 |
| Which runtime does it run on? (follow-up) | .NET 8 | correct | correct | 813 |
| Who is on call for the Platform team in calendar week 50? | Amara Okafor | wrong (week 48) | correct | 844 |
| What was the root cause of INC-2026-129? | Unbounded retry loop | correct | correct | 628 |
| What is the average salary in the Commerce team? | Not in the data | correct | correct | 892 |
| What did the Payment Gateway cost in September 2026? | 9,320 EUR | - | correct | 798 |
Every listed lookup was correct in this run, and the on-call question that failed with all data in the prompt is answered correctly. With five teams instead of seven files in front of it, the model picks the right week. The input shrinks from about 10,650 to 600-900 tokens.
The time to first token stays between 100 and 200 ms, but reading the input takes 50 to 190 ms instead of 17 ms. Part 2 profited from Ollama’s prompt cache because the long prefix never changed. With RAG, changing excerpts reduce the reusable prefix. Stable instructions and history can still be cached, but this run benefited mainly from the smaller input.
What the search actually finds
A /search <text> command that prints the ten best chunks with their scores is the most useful debugging tool in a RAG application. It shows what the model will see before the model sees it.
Searching an incident identifier exposes the limits of semantic similarity:
1search: INC-2026-129
2 0.308 incidents.json › INC-2026-127 · 2026-09-27
3 0.305 incidents.json › INC-2026-129 · 2026-10-14
4 0.302 incidents.json › INC-2026-128 · 2026-10-03
5 0.294 incidents.json › INC-2026-123 · 2026-08-19
6 ...All 31 incidents look alike to the embedding model, and the scores of the top ten differ by 0.02. For the full question “What was the root cause of INC-2026-129?”, the right incident lands in third place - inside the top 5, but by luck rather than by design. IDs, order numbers, version strings and error codes need an exact or keyword search. Combining both is called hybrid search.
The surrounding business context matters as well. Cost entries only contain a service ID such as svc-payment. For “What did the Payment Gateway cost in September 2026?”, the cost chunk of the API Gateway ranks first (0.372), the Payment Gateway second (0.365). The model still answered correctly, because svc-payment is a readable ID. With an opaque ID such as S-0042, semantic matching would have less useful information. Adding the service name to the chunk improves that representation; exact identifier lookups still need an exact match or structured query.
The scores do not establish whether an answer exists. The salary question, whose answer is not in the data, finds the Commerce team chunk with 0.349. The correct incident chunk for the root cause question scores 0.274. A fixed minimum score that filters out the irrelevant salary hit would also filter out the correct incident. Scores also differ between embedding models and can only be compared within one model.
The SLA question illustrates another consequence. All twelve service records rank between 0.406 and 0.429 for “Which services missed their SLA target in October 2026?” The Payment Gateway is one of the three expected results but appears in tenth place, outside a top-five retrieval.
Aggregations: RAG does not fix them
The aggregation questions from part 2 with the top 5 and, for comparison, the top 12 chunks:
| Question | Correct answer | RAG, top 5 | RAG, top 12 |
|---|---|---|---|
| Which services missed their SLA target in October 2026? | Payment Gateway, Search API, Notification Service | Search API, plus one service that met its target | Payment Gateway, plus two services that met their target |
| How many SEV1 incidents were there in 2026? | 4 | “4” - with only 3 SEV1 incidents in the sources | 8 |
| Total cloud costs of all services in September 2026? | 64,730 EUR | 31,480 - five services only, and wrongly added | 93,420 - all twelve values listed correctly, wrongly added |
| Which services run on a runtime whose support ends in 2026? | 5 services | 4 of 5 | 3 of 5, plus 2 on .NET 10 |
| Which projects are over budget? | PRJ-11, PRJ-14, PRJ-18 | All 5 found projects, 2 of them correct | correct |
The top 5 are the five most similar chunks, not all matching chunks. “Spent more than budget” requires evaluating a relation between two fields, which a similarity ranking does not reliably implement. A project that is over budget is not more similar to the question than one that is not. The search can only deliver a sample, and the model aggregates over that sample.
Twelve chunks bring completeness back for the project question, where every chunk carries its own answer: spent versus budget, row by row. Everywhere else, more chunks lead back to the problems of part 2 - the model sees all values and still adds or compares them wrongly.
The SEV1 answer with top 5 deserves a second look. “4” is correct, but the sources contained only three SEV1 incidents. The number cannot have come from the data the model received. Showing sources next to an answer does not prove that the answer came from them.
What it costs
| Part 2: all data in the prompt | Part 3: RAG, top 5 | |
|---|---|---|
| Input tokens per question | about 10,650 | 520 - 1,070 |
| Embedding at startup | - | 88 chunks, 13,758 tokens (embeddinggemma) |
| Embedding per question | - | the question, a few dozen tokens |
| Ollama models in memory | chat model with 16k context | chat model with 8k context plus embedding model |
With Microsoft Foundry and example prices of 0.40 US dollars per million input tokens for gpt-4.1-mini and 0.02 dollars for text-embedding-3-small:
- a question with about 800 input tokens costs about 0.0003 dollars, compared with 0.0042 dollars (or 0.0011 with prompt caching) for the data alone in part 2;
- indexing all chunks takes 11,070 tokens with the tokenizer of
text-embedding-3-small, about 0.0002 dollars per start; - prompt caching no longer applies: most RAG prompts here are shorter than the 1,024-token minimum, and the data changes with every question.
Embedding usage is reported like chat usage. A DelegatingEmbeddingGenerator - the embedding counterpart to the IChatClient middleware from part 1 - can count it without touching the index:
1public sealed class EmbeddingTokenCounter(IEmbeddingGenerator<string, Embedding<float>> innerGenerator)
2 : DelegatingEmbeddingGenerator<string, Embedding<float>>(innerGenerator)
3{
4 public long InputTokens { get; private set; }
5
6 public override async Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(
7 IEnumerable<string> values,
8 EmbeddingGenerationOptions? options = null,
9 CancellationToken cancellationToken = default)
10 {
11 GeneratedEmbeddings<Embedding<float>> embeddings = await base.GenerateAsync(values, options, cancellationToken);
12 InputTokens += embeddings.Usage?.InputTokenCount ?? 0;
13
14 return embeddings;
15 }
16}In memory or a vector database?
A list of vectors in memory is the right choice when the data is shipped with the application, fits into a few thousand chunks and can be re-embedded on every start. The math stays friendly for a while: 100,000 chunks with 1,536 dimensions take about 586 MiB - but also need 100,000 embeddings on every start.
Persistence becomes useful when changed chunks should be updated incrementally or several application instances need a shared index. Larger collections may also need metadata filtering, keyword search or a faster nearest-neighbor index. Those requirements can be met by a relational database or search service with vector support as well as by a dedicated vector database.
Microsoft.Extensions.VectorData
provides a common abstraction for vector stores, with providers for Azure AI Search, PostgreSQL, SQL Server, Azure Cosmos DB and others. CommunityToolkit.VectorData.InMemory implements the same abstraction in memory and is a good replacement for a hand-written index during prototyping. The documentation recommends testing against the real database, because the in-memory provider can behave differently.
Retrieval decides what the model knows
In these runs, retrieval reduced input size and improved several lookups. It also introduced a new reason for an answer to fail: the relevant record might never reach the model. Similar identifiers and questions about every matching entry were particularly revealing cases.
Retrieval quality therefore needs its own evaluation, with the selected chunks visible alongside the final answer. A larger result set can sometimes recover missing evidence, but it cannot make a similarity ranking behave like an exact query. Counts, totals and field comparisons are better computed explicitly and supplied as results.
Further reading
Related articles

- 15 min read
Chat with Local Data: Context Stuffing with IChatClient
Series - AI chat applications with .NET: Part 1: A Console Chat with IChatClient · Part 2: Chat with Local Data

- 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 …
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.
