Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 13 of 39
❮Prev Next❯

Retrieval-Augmented Generation (RAG) in an App

Module 2: GenAI & Agents ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    Retrieval-augmented generation (RAG) looks up your own content first and then asks the model to answer from it. You chunk documents, embed each chunk, store them in an Azure AI Search index, then at query time run a hybrid (keyword plus vector) search, put the top chunks in the prompt and ask for citations. Use the same embedding model for the index and the query, and tell the model to say it doesn't know when the sources don't cover the question.

    Simulate it » No Azure account needed

    Exam objective: 2.1.2 Implement retrieval-augmented generation (RAG) in an application. (Skills measured as of April 16, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Ground an answer on your own documents with Azure AI Search Connect Azure AI Search and ground an answer on your documents.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open <strong>Settings ➜ Connected resources</strong> and add a connection to <strong>Azure AI Search</strong>.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open Settings ➜ Connected resources and add a connection to Azure AI Search.
    2. Choose the search service and Microsoft Entra ID as the authentication method. The project’s managed identity needs Search Index Data Reader on the service.
    3. The documents were split into chunks (about 500 tokens with a small overlap), embedded, and uploaded to policies-index. Open it.
    4. Try a query. Hybrid search combines keywords and vectors, and returns the top chunks with their source file.
    5. In the chat playground add your data and test. The reply cites the chunk it used. Ask something the documents don’t cover, and it should say it doesn’t know.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    The chatbot answers return questions with a confident guess about a policy it has never read.

    😊 THE SOLUTION

    Retrieve the right policy chunks first and make the model answer from them with citations.

    • Guessed answers✓ Put retrieved chunks in the prompt
    • Keyword search misses the paraphrase✓ Hybrid search: keywords plus vectors
    • Invented answers when nothing matches✓ Instruct it to say “I don’t know”
    🛠️ Solved with: Retrieval-augmented generation with Azure AI Search

    Start with a question

    Would you answer an exam question from memory or with the book open?

    If a friend asks “how many days do I get to return a damaged kettle?” about a shop you’ve never visited, you’d guess. If you open the shop’s policy page first, you’d read the answer out.

    A model without retrieval is the friend guessing. RAG opens the right page first. The app finds the best pieces of your documents, puts them in front of the model and asks it to answer from them.

    Explain it like I’m 10

    The technical explanation

    Two phases

    Ingestion happens before any question:

    1. Read the documents and split them into chunks, for example about 500 tokens with a 50-token overlap.
    2. Embed each chunk with an embedding model such as text-embedding-3-small.
    3. Upload the text, the source name and the vector to an Azure AI Search index.

    Query happens for every question:

    1. Run a hybrid search: keywords plus a vector query for the question.
    2. Take the top few chunks.
    3. Put them in the prompt with the rule “answer from the sources and cite them”.
    4. Send it to the chat deployment and return the answer with its citations.
    conn = project.connections.get("search-contoso")          # target comes from the project
    search = SearchClient(endpoint=conn.target, index_name="policies-index", credential=cred)
    hits = search.search(search_text=question,
                         vector_queries=[VectorizableTextQuery(text=question, k_nearest_neighbors=3, fields="contentVector")],
                         top=3)
    sources = "\n".join(f"[{h['source']}#{h['chunk']}] {h['content']}" for h in hits)
    
    r = openai.responses.create(
        model="support-chat",
        instructions="Answer from the sources and cite them like [file#chunk]. "
                     "If the sources don't contain the answer, say you don't know.\n\nSources:\n" + sources,
        input=question, temperature=0.2)

    What makes it work

    PartWhat to decideWhat goes wrong
    ChunkingSize and overlapChunks that start mid-sentence lose their meaning
    Embedding modelOne model for index and queriesDifferent models give vectors you can’t compare
    Search typeHybrid, often with a semantic rankerVector-only misses exact codes
    Top KHow many chunks go in the promptToo few misses the answer, too many adds noise and cost
    PromptAnswer only from sources, cite, admit gapsThe model fills the gaps with a guess

    Foundry also offers a managed route: a Foundry IQ knowledge base on Azure AI Search plans sub-queries and returns grounded passages with citations. The same ideas apply, and you can use it instead of building the retrieval yourself.

    Documents are content from outside your app. They can hide instructions that try to steer the model, which is an indirect attack, so scan retrieved content and evaluate for it.

    Architect level Why an honest I don't know matters

    When retrieval returns nothing useful, a model that was never told to refuse will still produce a fluent answer. Put the refusal rule in the instructions, return source IDs so answers can be checked, and score groundedness on a test set that includes questions your documents can’t answer. That test set is what catches the confident invention before a customer does.

    Real-world business scenario

    Retail

    Contoso Retail (fictional)

    The problem
    The support chatbot told customers they had 30 days to return damaged kettles. The real policy was 10 days, and it changed again each quarter.
    What they used
    Policy PDFs chunked and embedded into an Azure AI Search index, hybrid retrieval with the top three chunks, and a chat deployment instructed to cite sources and say it doesn't know. The index refreshes whenever a policy file changes.
    Why that choice
    The answer now comes from the current document, carries a citation, and updates when the file does, without retraining anything.
    The result
    Wrong-policy complaints dropped, and agents could check any answer by opening the cited chunk.

    When to use it and when not to

    ✓ Use it when…

    • Answers must come from your own documents, with citations.
    • The content changes often.
    • Different users need different documents, controlled by access to the index.

    ✕ Think twice when…

    • The answer is one exact value in a database. Query it with a function.
    • You want to change tone or format only. Better instructions do that.
    • The model already knows the public fact and a source adds nothing.

    ↔ Alternatives to consider

    • Function calling for live records in a system.
    • File search for documents a user uploads in a conversation.
    • Foundry IQ knowledge base for managed, multi-source retrieval.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-103 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    A returns policy changes every week. The chatbot must answer from the current policy and cite the document.

    Which approach should you use?

    Question 2

    Question 2 of 5

    Users search for exact product codes such as KX-4420 and also ask paraphrased questions such as "my kettle stopped heating".

    Which retrieval method best supports both?

    Question 3

    Question 3 of 5

    Retrieved chunks often start mid-sentence, and answers lack the surrounding context.

    What should you adjust in the ingestion process?

    Question 4

    Question 4 of 5 · Select 2

    A support bot must avoid inventing policy details when retrieval returns nothing useful.

    Which two actions should you take? Select two.

    Question 5

    Question 5 of 5

    An index stores vectors created with text-embedding-3-small. Queries return poor matches after a developer embeds the query with a different embedding model.

    What is the cause?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner What problem does RAG solve?

    Model answer

    A model only knows what it was trained on, so it guesses about your private or recent content. RAG fetches the right pieces of your own documents first and gives them to the model, so the answer comes from them and can carry a citation.

    Intermediate Why use hybrid search instead of vectors alone?

    Model answer

    Vectors find meaning, so a paraphrased question matches. They can miss exact codes such as a part number. Keywords catch those. Hybrid runs both and merges the results, which handles both kinds of question.

    Experienced developer Retrieval looks right but answers are still poor. Where do you look?

    Model answer

    I check chunking first, because bad boundaries lose context. Then the embedding model, which must be the same for ingestion and queries. Then top-k and ranking, then the prompt, and finally I score groundedness and relevance on a test set instead of guessing.

    Scenario The policy changes every week. Should we fine-tune?

    Model answer

    No. I would keep the policy in an index and refresh it, so the answers change when the documents do. Fine-tuning is slow, costs more and is not a reliable way to add facts.

    Quick revision

    Key points

    • RAG retrieves first, adds the chunks to the prompt, then generates.
    • Chunk size and overlap decide what retrieval can return.
    • Hybrid search combines keyword and vector queries.
    • Query and index vectors must come from the same embedding model.
    • Tell the model to answer only from sources and to say it does not know.

    Important terminology

    RAG
    A pattern that retrieves relevant content and adds it to the prompt so the model answers from it instead of guessing.
    Chunk
    A piece of a document, often about 500 tokens with a small overlap, that is embedded and stored as one search item.
    Embedding
    A vector of numbers that captures meaning, so similar texts end up close together.
    Hybrid search
    A query that combines keyword matching and vector similarity, then merges the rankings.
    Citation
    A pointer from a sentence in the answer to the source chunk that supports it.
    Grounding
    Tying an answer to supplied sources so each claim can be checked.

    Common mistakes

    • Embedding the query with a different model than the index.
    • Chunks that start mid-sentence and lose context.
    • Letting the model answer when retrieval returned nothing.

    Exam tips

    • "Answer from current company documents with citations" = RAG, not fine-tuning.
    • "Exact product codes and paraphrases" = hybrid search.
    • "Vectors do not match" = check the same embedding model for both sides.

    Five quick revision questions

    1. 1.What are the two phases of RAG?Show

      Ingestion (chunk, embed, index) and query (retrieve, augment, generate).

    2. 2.Which search type mixes keywords and vectors?Show

      Hybrid search.

    3. 3.Which model embeds the query?Show

      The same one used for the index.

    4. 4.What should the model say with no sources?Show

      That it does not know.

    5. 5.What lets a user check a claim?Show

      A citation to the source chunk.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Workflows, Tool-Augmented Flows and Multistep Reasoning

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.