Retrieval-Augmented Generation (RAG)
A model knows what it learned in training, not your opening hours, your prices or your policies. Retrieval-augmented generation, RAG for short, finds the parts of your own documents that fit a question and gives them to the model with it, so it answers from them, and says so when they don't answer. This tutorial builds a museum guide that searches the five pages of a visitor guide and answers from what it finds.
How RAG Works
Retrieve, then generate
RAG adds one step before the model: a search of your documents. Whatever the search finds goes into the request, next to the question:
The model still writes the answer, but from text you gave it, which you can check and update without retraining anything. Microsoft's RAG guide for Agent Framework describes two ways to give the agent that text: context providers that add retrieved content before model invocation and search tools that let the model retrieve grounding data on demand.
Searching by meaning
A visitor who asks Can I use a flash? means the page about photography, although the word photography isn't in the question. A search by meaning finds it with embeddings. An embedding model turns a text into a vector, a long list of numbers, and Microsoft's embeddings guide explains the point of it: Similar text produces vectors that are close together. text-embedding-3-small gives 1,536 numbers for any text.
How close two vectors are is measured with cosine similarity: a number up to 1, where higher means closer in meaning. The search embeds each page once, embeds each question, and picks the pages whose vectors are most similar to the question's. A real app keeps the vectors in a vector database or a search service; five pages fit in an array.
Where Agent Framework fits
TextSearchProvider is Agent Framework's ready-made RAG component. It's a context provider, like the ones in Context Providers and Memory: it adds information to the agent's runs. You give it a search function, and it decides when to call it:
SearchTime | What happens |
|---|---|
BeforeAIInvoke (the default) | It searches with the question before every model call and adds the results to the request |
OnDemandFunctionCalling | It gives the model a search tool, named Search, and the model decides when to search, and for what |
Each result can carry the name and the link of the page it came from. Microsoft's guide: SourceName and SourceLink are optional, but if provided will be used by the agent to cite the source of the information when answering the user's question.
The search function is yours, so the search can be anything: a vector database, Azure AI Search, a web search, or the small search in this tutorial.
The Example
A console app called MuseumGuide answers visitors' questions about a city museum from five pages of its visitor guide: opening hours, tickets and prices, photography, accessibility, and the cloakroom. It embeds the pages once at startup, then:
- Asks three questions with
BeforeAIInvoke: one the photography page answers, one that needs a small calculation from the prices page, and one the guide doesn't answer. - Says hello and asks one question with
OnDemandFunctionCalling, to see when the model chooses to search.
What It Costs
The chat model is gpt-5.6-luna, at $0.20 per million input tokens and $1.20 per million output tokens. A question with its search results was about 245 input tokens in my run. The embedding model, text-embedding-3-small, cost $0.02 per million tokens at the time of writing, and the five pages and five questions are a few hundred tokens: a tiny fraction of a cent. The whole run cost well under a tenth of a cent.
Prerequisites
- The agent from Runtime Model Routing, and the setup it uses: the .NET 10 SDK, the Azure CLI signed in, a Foundry project endpoint and a chat model deployment.
- An embedding model deployment, such as
text-embedding-3-small, in the same Foundry resource. Microsoft's embeddings guide asks for the Cognitive Services OpenAI User role on the resource for signing in with Microsoft Entra ID.
Step 1: Create a Console App
In a terminal, in the folder where you keep your projects, run:
dotnet new console -n MuseumGuide
cd MuseumGuide
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0
dotnet add package System.Numerics.Tensors --version 10.0.15
Microsoft.Agents.AI.Foundry, a preview, brings in TextSearchProvider and the OpenAI library. System.Numerics.Tensors adds TensorPrimitives, which computes cosine similarity.
Step 2: The Documents
Replace everything in Program.cs with the usings, the project's OpenAI client and the guide:
using System.ClientModel.Primitives;
using System.Numerics.Tensors;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Embeddings;
AzureCliCredential credential = new();
var openAI = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
credential)
.GetProjectOpenAIClient();
// The museum's visitor guide: the documents the agent answers from.
GuidePage[] guide =
[
new("Opening hours", "https://example.com/guide/opening-hours",
"The museum is open Tuesday to Sunday from 10:00 to 18:00, and until 21:00 on Thursdays. It is closed on Mondays, except on public holidays."),
new("Tickets and prices", "https://example.com/guide/tickets",
"Adult tickets cost €14. Students and visitors over 65 pay €9, and children under 12 enter free. Tickets bought online are €2 cheaper."),
new("Photography", "https://example.com/guide/photography",
"You may take photos for personal use in the permanent collection. Flash, tripods and selfie sticks are not allowed. Photography is not allowed in temporary exhibitions."),
new("Accessibility", "https://example.com/guide/accessibility",
"Every floor can be reached by lift. You can borrow a wheelchair for free at the information desk. Assistance dogs are welcome."),
new("Cloakroom and lockers", "https://example.com/guide/cloakroom",
"Coats and bags larger than A4 must be left in the cloakroom, which is free. The lockers take a €1 coin, which you get back."),
];
Each page has a name, a link and its text, held in a small record at the end of the file: record GuidePage(string Name, string Link, string Text);. In a real app, the pages come from your files or a database, split into pieces small enough to search one by one.
Step 3: Turn the Documents into Vectors
// An embedding model turns text into a list of numbers, a vector. Texts with similar meanings get similar vectors.
// Embeddings go to the resource's Azure OpenAI endpoint: the project endpoint doesn't route embedding requests.
// This constructor is experimental in the OpenAI library (OPENAI001), so its API can still change.
#pragma warning disable OPENAI001
EmbeddingClient embeddingClient = new(
model: "text-embedding-3-small",
authenticationPolicy: new BearerTokenPolicy(credential, "https://ai.azure.com/.default"),
options: new OpenAIClientOptions { Endpoint = new Uri("https://foundry-devblogs-exp.openai.azure.com/openai/v1/") });
#pragma warning restore OPENAI001
IEmbeddingGenerator<string, Embedding<float>> embeddings = embeddingClient.AsIEmbeddingGenerator();
// Embed every page once, when the app starts.
GeneratedEmbeddings<Embedding<float>> pageVectors = await embeddings.GenerateAsync(guide.Select(page => page.Text));
- The resource's endpoint, not the project's. The chat model goes through the project's OpenAI client, as before, but embeddings can't. Microsoft's guide to Foundry's endpoints: The project endpoint used by the Foundry SDK doesn't currently route embedding requests. My first version asked the project's client for embeddings and stopped with
Service request failed. Status: 404 (Not Found), which Fixed: "Service request failed. Status: 404 (Not Found)" Generating Embeddings from a Microsoft Foundry Project walks through. Use your own resource's name, the part before.services.ai.azure.comin your project endpoint. BearerTokenPolicysigns each request in with your Azure CLI account, for thehttps://ai.azure.com/.defaultscope, as Microsoft's embeddings guide does.#pragma warning disable OPENAI001accepts the experimental constructor, as Microsoft's own code does. Without it, the build fails with OPENAI001.AsIEmbeddingGenerator()turns the client into Microsoft.Extensions.AI'sIEmbeddingGenerator, andGenerateAsyncembeds all five pages in one request.pageVectors[i]is the vector of pagei.
How to Generate Embeddings from a Microsoft Foundry Resource in C# shows embeddings on their own.
Step 4: The Search Function
Add the search at the end of the file, above the record:
// The search: embed the question, and return the two pages whose vectors are most similar to it.
async Task<IEnumerable<TextSearchProvider.TextSearchResult>> SearchGuideAsync(string query, CancellationToken cancellationToken)
{
ReadOnlyMemory<float> queryVector = await embeddings.GenerateVectorAsync(query, cancellationToken: cancellationToken);
var best = guide
.Select((page, index) => (Page: page, Score: TensorPrimitives.CosineSimilarity(queryVector.Span, pageVectors[index].Vector.Span)))
.OrderByDescending(match => match.Score)
.Take(2)
.ToList();
Console.WriteLine($" Searched for: {query}");
Console.WriteLine($" Found: {string.Join(", ", best.Select(match => $"{match.Page.Name} ({match.Score:0.00})"))}");
return best.Select(match => new TextSearchProvider.TextSearchResult
{
SourceName = match.Page.Name,
SourceLink = match.Page.Link,
Text = match.Page.Text,
});
}
- The signature is the one
TextSearchProviderasks for: it gets the text to search for and returns the results. GenerateVectorAsyncembeds the question.TensorPrimitives.CosineSimilaritycompares the question's vector with each page's, and the two highest scores win. It always returns two pages, even when neither fits: deciding whether they answer the question is the model's job, and the instructions in Step 5 tell it what to do then.- The two
Console.WriteLinelines show what the search did, for this tutorial. TextSearchResultcarries each page's text, with its name and link for citations.

Step 5: Give the Agent the Search
Add a function that creates the guide agent, after the vectors:
AIAgent CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior searchTime) => openAI
.GetChatClient("gpt-5.6-luna")
.AsIChatClient()
.AsAIAgent(new ChatClientAgentOptions
{
Name = "MuseumGuide",
ChatOptions = new ChatOptions
{
Instructions = "You are the City Museum's guide, and you answer visitors' questions about the museum in one or " +
"two sentences of plain text, without Markdown. Answer only from the museum's guide, and name the page you " +
"used. If the guide doesn't answer the question, say that you don't know. When a visitor greets you, greet " +
"them and say what you can help with.",
},
AIContextProviders = [new TextSearchProvider(SearchGuideAsync, new TextSearchProviderOptions { SearchTime = searchTime })],
});
new TextSearchProvider(SearchGuideAsync, ...)wraps the search function, andAIContextProvidersattaches it to the agent.SearchTimecomes from the caller, so the same function creates an agent for each mode.- The instructions keep the agent to the guide: Answer only from the museum's guide, name the page, and say I don't know when the guide is silent. The last sentence is there because of what my first run did in Step 7.
- Chat Completions, as in the previous tutorials: each question here is asked on its own, and the service keeps nothing.
Then a small helper that asks one question and prints the answer and its input tokens, after the agent function:
async Task AskAsync(AIAgent agent, string question)
{
Console.WriteLine($"Q: {question}");
AgentResponse answer = await agent.RunAsync(question);
Console.WriteLine($"A: {answer.Text}");
Console.WriteLine($" {answer.Usage?.InputTokenCount} input tokens");
Console.WriteLine();
}
Step 6: Ask the Questions
Add the questions after the vectors, before the agent function:
// 1. Search before every model call, and add the best pages to the request.
AIAgent guideAgent = CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke);
await AskAsync(guideAgent, "Can I use a flash when I take photos?");
await AskAsync(guideAgent, "I'm 70. How much is my ticket if I buy it online?");
await AskAsync(guideAgent, "Is there a café in the museum?");
// 2. Give the model a search tool instead, and let it decide when to search.
AIAgent onDemandAgent = CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior.OnDemandFunctionCalling);
await AskAsync(onDemandAgent, "Hi! Who are you?");
await AskAsync(onDemandAgent, "Is the museum open on Mondays?");
The complete file:
using System.ClientModel.Primitives;
using System.Numerics.Tensors;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Embeddings;
AzureCliCredential credential = new();
var openAI = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
credential)
.GetProjectOpenAIClient();
// The museum's visitor guide: the documents the agent answers from.
GuidePage[] guide =
[
new("Opening hours", "https://example.com/guide/opening-hours",
"The museum is open Tuesday to Sunday from 10:00 to 18:00, and until 21:00 on Thursdays. It is closed on Mondays, except on public holidays."),
new("Tickets and prices", "https://example.com/guide/tickets",
"Adult tickets cost €14. Students and visitors over 65 pay €9, and children under 12 enter free. Tickets bought online are €2 cheaper."),
new("Photography", "https://example.com/guide/photography",
"You may take photos for personal use in the permanent collection. Flash, tripods and selfie sticks are not allowed. Photography is not allowed in temporary exhibitions."),
new("Accessibility", "https://example.com/guide/accessibility",
"Every floor can be reached by lift. You can borrow a wheelchair for free at the information desk. Assistance dogs are welcome."),
new("Cloakroom and lockers", "https://example.com/guide/cloakroom",
"Coats and bags larger than A4 must be left in the cloakroom, which is free. The lockers take a €1 coin, which you get back."),
];
// An embedding model turns text into a list of numbers, a vector. Texts with similar meanings get similar vectors.
// Embeddings go to the resource's Azure OpenAI endpoint: the project endpoint doesn't route embedding requests.
// This constructor is experimental in the OpenAI library (OPENAI001), so its API can still change.
#pragma warning disable OPENAI001
EmbeddingClient embeddingClient = new(
model: "text-embedding-3-small",
authenticationPolicy: new BearerTokenPolicy(credential, "https://ai.azure.com/.default"),
options: new OpenAIClientOptions { Endpoint = new Uri("https://foundry-devblogs-exp.openai.azure.com/openai/v1/") });
#pragma warning restore OPENAI001
IEmbeddingGenerator<string, Embedding<float>> embeddings = embeddingClient.AsIEmbeddingGenerator();
// Embed every page once, when the app starts.
GeneratedEmbeddings<Embedding<float>> pageVectors = await embeddings.GenerateAsync(guide.Select(page => page.Text));
// 1. Search before every model call, and add the best pages to the request.
AIAgent guideAgent = CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke);
await AskAsync(guideAgent, "Can I use a flash when I take photos?");
await AskAsync(guideAgent, "I'm 70. How much is my ticket if I buy it online?");
await AskAsync(guideAgent, "Is there a café in the museum?");
// 2. Give the model a search tool instead, and let it decide when to search.
AIAgent onDemandAgent = CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior.OnDemandFunctionCalling);
await AskAsync(onDemandAgent, "Hi! Who are you?");
await AskAsync(onDemandAgent, "Is the museum open on Mondays?");
AIAgent CreateGuideAgent(TextSearchProviderOptions.TextSearchBehavior searchTime) => openAI
.GetChatClient("gpt-5.6-luna")
.AsIChatClient()
.AsAIAgent(new ChatClientAgentOptions
{
Name = "MuseumGuide",
ChatOptions = new ChatOptions
{
Instructions = "You are the City Museum's guide, and you answer visitors' questions about the museum in one or " +
"two sentences of plain text, without Markdown. Answer only from the museum's guide, and name the page you " +
"used. If the guide doesn't answer the question, say that you don't know. When a visitor greets you, greet " +
"them and say what you can help with.",
},
AIContextProviders = [new TextSearchProvider(SearchGuideAsync, new TextSearchProviderOptions { SearchTime = searchTime })],
});
async Task AskAsync(AIAgent agent, string question)
{
Console.WriteLine($"Q: {question}");
AgentResponse answer = await agent.RunAsync(question);
Console.WriteLine($"A: {answer.Text}");
Console.WriteLine($" {answer.Usage?.InputTokenCount} input tokens");
Console.WriteLine();
}
// The search: embed the question, and return the two pages whose vectors are most similar to it.
async Task<IEnumerable<TextSearchProvider.TextSearchResult>> SearchGuideAsync(string query, CancellationToken cancellationToken)
{
ReadOnlyMemory<float> queryVector = await embeddings.GenerateVectorAsync(query, cancellationToken: cancellationToken);
var best = guide
.Select((page, index) => (Page: page, Score: TensorPrimitives.CosineSimilarity(queryVector.Span, pageVectors[index].Vector.Span)))
.OrderByDescending(match => match.Score)
.Take(2)
.ToList();
Console.WriteLine($" Searched for: {query}");
Console.WriteLine($" Found: {string.Join(", ", best.Select(match => $"{match.Page.Name} ({match.Score:0.00})"))}");
return best.Select(match => new TextSearchProvider.TextSearchResult
{
SourceName = match.Page.Name,
SourceLink = match.Page.Link,
Text = match.Page.Text,
});
}
record GuidePage(string Name, string Link, string Text);
Step 7: Run It
dotnet run
Q: Can I use a flash when I take photos?
Searched for: Can I use a flash when I take photos?
Found: Photography (0.54), Cloakroom and lockers (0.08)
A: No, flash photography is not allowed. Source: Photography (https://example.com/guide/photography).
249 input tokens
Q: I'm 70. How much is my ticket if I buy it online?
Searched for: I'm 70. How much is my ticket if I buy it online?
Found: Tickets and prices (0.49), Accessibility (0.16)
A: Your online ticket costs €7, since visitors over 65 pay €9 and online tickets are €2 cheaper. Source: Tickets and prices — https://example.com/guide/tickets
243 input tokens
Q: Is there a café in the museum?
Searched for: Is there a café in the museum?
Found: Opening hours (0.44), Photography (0.32)
A: I don’t know; the provided guide pages on Opening hours (https://example.com/guide/opening-hours) and Photography (https://example.com/guide/photography) do not mention a café.
249 input tokens
Q: Hi! Who are you?
A: Hello! I’m the City Museum’s guide, and I can help you learn about our exhibits and visitor information.
214 input tokens
Q: Is the museum open on Mondays?
Searched for: Is the museum open on Mondays?
Found: Opening hours (0.73), Photography (0.31)
A: The museum is closed on Mondays, except on public holidays. Source: Opening hours (https://example.com/guide/opening-hours).
626 input tokens

Searching before every model call
- The flash question found the photography page with a score of 0.54, far ahead of the next page at 0.08, though the question never says photography. The answer is the guide's rule, with the page's name and link.
- The ticket question found the prices page, and the model did the small sum itself: €9 for visitors over 65, €2 less online, so €7. Retrieval gives the model the facts, and it can still reason with them.
- The café question also found two pages, because the search always returns two, but they score low and say nothing about a café. The model said it didn't know, instead of inventing one. That's what the instructions are for.
Each answer cost about 245 input tokens: the instructions, the question and the two pages that TextSearchProvider added. By default, it adds them under the heading ## Additional Context, with an instruction to cite the source document, and that's why every answer names its page.
Searching on demand
With OnDemandFunctionCalling, the model gets a search tool and calls it only when it decides to:
- The greeting ran no search at all, in one model call of 214 input tokens.
- The Monday question made the model call the tool, and the search found the opening hours page. That took two model calls, one to ask for the search and one to answer, which is why it used 626 input tokens. The model chooses what to search for: here it searched with the question as written.
My first run's instructions said neither who the agent is nor what to do with a greeting: they began with You answer visitors' questions about the City Museum and ended with the rule to say I don't know. The model then searched even for Hi! Who are you?, found nothing about itself, and answered I don’t know; the museum guide does not identify who I am., in 565 input tokens. Answer only from the museum's guide left it no other way to answer a greeting. With instructions that say who it is and what to do with a greeting, it answered without searching.
So: BeforeAIInvoke costs one model call and always searches. OnDemandFunctionCalling skips the search when it isn't needed, and pays a second model call when it is.
What You Can Do Now
- Explain how RAG grounds an answer in your own documents, and what embeddings and cosine similarity do in the search.
- Embed documents with an embedding model on your Foundry resource, and find the closest ones to a question.
- Attach a search to an agent with
TextSearchProvider, and choose between searching before every model call and searching on demand. - Get answers that name their sources, and that say I don't know when your documents don't answer.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Asking the project's OpenAI client for embeddings | Service request failed. Status: 404 (Not Found) (Fixed) | Use the resource's /openai/v1/ endpoint, as in Step 3 |
| Embedding the pages on every question | Every question pays to embed the whole guide again | Embed the pages once, and only the question each time |
| Leaving out what to do when the guide is silent | The model can fill the gap from its training | Tell it to say that it doesn't know |
| Forbidding everything outside the documents in on-demand mode | The model searches even for a greeting, as in my first run | Say what to do with messages the documents don't cover, such as greetings |
| Trusting retrieved text blindly | The API documentation warns that retrieved documents may contain adversarial content designed to manipulate LLM behavior via indirect prompt injection | Search only documents you control, and keep the agent's tools limited |
Frequently Asked Questions
Do I need a vector database?
Not for a handful of pages: an array and TensorPrimitives are enough, as here. For many documents, a vector database or a search service such as Azure AI Search stores the vectors and searches them quickly, and your search function calls it instead.
Why does every answer name its page?
TextSearchProvider adds an instruction to the results: by default, its CitationsPrompt is Include citations to the source document with document name and link if document name and link is available. That's where the page names and links in the answers come from.
Which mode should I use?
BeforeAIInvoke when nearly every message needs the documents, as on a help page: one model call each time. OnDemandFunctionCalling when many messages don't, as in a general chat: no search for those, but a second model call when the model does search.
Can the search use the earlier messages of a conversation?
Yes. RecentMessageMemoryLimit keeps that many recent messages and adds them to the text it searches for in BeforeAIInvoke mode, so a follow-up such as and on Sundays? still finds the right page. It's off by default.
Conclusion
RAG lets an agent answer from your documents. An embedding model turns each page into a vector once, the search finds the pages closest in meaning to each question, and TextSearchProvider gives them to the model with their names and links, before every model call or only when the model asks for them. The answers come from your pages, name them, and say when the pages don't answer.
Next: Agent Skills (coming soon) — load reusable instructions, resources and scripts only when they're needed.
Additional Resources
- RAG —
TextSearchProviderand its options. - TextSearchProvider class — the API reference, with its security remarks.
- Generate embeddings with Azure OpenAI — the embeddings endpoint and its code.
- Microsoft Foundry SDKs and endpoints — which endpoint serves what.
- Embeddings in .NET — what embeddings are and where to store them.