Retrieval-Augmented Generation (RAG) in an App
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 neededExam 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.
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
- Open Settings ➜ Connected resources and add a connection to Azure AI Search.
- 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.
- The documents were split into chunks (about 500 tokens with a small overlap), embedded, and uploaded to policies-index. Open it.
- Try a query. Hybrid search combines keywords and vectors, and returns the top chunks with their source file.
- 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.
🖱️ Drag to rotate · scroll or pinch to zoom
RAG: retrieve first, then answer
Retrieval-augmented generation searches your own content (Azure AI Search, hybrid keyword plus vector), puts the best chunks in the prompt and asks the model to answer from them with citations. Without retrieval the model guesses.
🤔 What happens if…
Read this tour as text
- Deploy a model, call the deployment. A deployment is a named copy of a model with a version, a deployment type and capacity. Your app calls the deployment name, never the model name. Pick a large model for hard work and a small language model for cheap, fast, simple work.
- RAG: retrieve first, then answer. Retrieval-augmented generation searches your own content (Azure AI Search, hybrid keyword plus vector), puts the best chunks in the prompt and asks the model to answer from them with citations. Without retrieval the model guesses.
- A multistep flow with checks. A workflow breaks one big request into steps you control: classify, extract to a JSON schema, call a tool, draft, then verify. Retries, fallbacks and a final check live in code, so one bad step can’t slip through unseen.
- Evaluate before you ship. Evaluators score each answer on a test set: groundedness (is it supported by the context?), relevance, coherence and safety checks. A fabrication shows up as a low groundedness score on one row, so you fix it before users see it.
- SDK, project endpoint and connections. The Foundry SDK (
azure-ai-projects) opens one door: AIProjectClient with the project endpoint and DefaultAzureCredential. From it your app gets an OpenAI-compatible client, deployments and connections (Azure AI Search, Application Insights) with no secrets in code. - Design the agent: role, goal, tool schema. An agent is a model plus instructions (role and goal), tools and a conversation (thread). A strict function schema names each parameter and marks the required ones, so the model asks the user instead of inventing a value.
- Retrieval, function calling and memory. One agent can use file search for documents, a function for live data and memory for what it learned about a user. The model asks to call a function; your code runs it and returns the result. Memory survives into a new conversation.
- Multi-agent orchestration. Several specialist agents can share a job. Sequential passes work down a line, concurrent fans out and merges, handoff moves control to the right specialist, group chat lets agents take turns in one shared conversation and Magentic lets a manager agent plan and delegate. Microsoft Agent Framework builds all five.
- Autonomy with approvals. Reads are safe, writes are not. A tool marked approval required pauses the run until a person decides. A hard limit in code blocks what no one should approve, whatever the model says.
- Monitor and debug agent runs. Agent evaluators read the whole run: intent resolution, tool call accuracy and task adherence. Error analysis groups the failing rows, such as a made-up tool argument, and points to the fix.
- Tune prompts and parameters. Instructions shape tone and rules, a few-shot example shows the format, temperature and top_p change how adventurous the wording is, and max output tokens caps length. A self-critique loop drafts, checks against a checklist and revises once.
- Trace every call and count tokens. OpenTelemetry spans record each agent run, model call and tool call, with tokens and latency, and Application Insights stores them. Tracing is opt-in, and recording message content is for development only because it captures prompts and answers.
- Route requests to the right model. A hybrid design puts rules first for answers code can decide, a small model for easy language work and a large or reasoning model only when needed. A model router can pick for you. Fewer big-model calls means a lower bill and faster replies.
The Contoso chatbot guesses return policies. Connect Azure AI Search, ingest the policy documents, compare an answer with and without retrieval, then score a dataset to find the fabricated reply and check safety.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 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”
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:
- Read the documents and split them into chunks, for example about 500 tokens with a 50-token overlap.
- Embed each chunk with an embedding model such as
text-embedding-3-small. - Upload the text, the source name and the vector to an Azure AI Search index.
Query happens for every question:
- Run a hybrid search: keywords plus a vector query for the question.
- Take the top few chunks.
- Put them in the prompt with the rule “answer from the sources and cite them”.
- 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
| Part | What to decide | What goes wrong |
|---|---|---|
| Chunking | Size and overlap | Chunks that start mid-sentence lose their meaning |
| Embedding model | One model for index and queries | Different models give vectors you can’t compare |
| Search type | Hybrid, often with a semantic ranker | Vector-only misses exact codes |
| Top K | How many chunks go in the prompt | Too few misses the answer, too many adds noise and cost |
| Prompt | Answer only from sources, cite, admit gaps | The 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
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.
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.
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.What are the two phases of RAG?Show
Ingestion (chunk, embed, index) and query (retrieve, augment, generate).
-
2.Which search type mixes keywords and vectors?Show
Hybrid search.
-
3.Which model embeds the query?Show
The same one used for the index.
-
4.What should the model say with no sources?Show
That it does not know.
-
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
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.