Implementing Retrieval-Augmented Generation in an Application
This lesson shows how an application implements retrieval-augmented generation (RAG), the most common pattern in AI-103 scenarios, with Azure AI Search and a Foundry model, so the model can answer from private, current content and cite its sources.
Learning outcomes
After completing this lesson, you will be able to:
- Explain why RAG, rather than fine-tuning, gives a model current and private knowledge.
- Describe the steps of a RAG request.
- Write a hybrid query with semantic ranking using azure-search-documents.
- Choose a tuning adjustment from a RAG symptom.
Why applications need retrieval
A language model answers from the knowledge it absorbed during training. That knowledge has a cut-off date, and it never included the organization's own documents: its policies, contracts, product manuals or support tickets. When a model is asked about such content, it either declines or, worse, produces a plausible answer that is not supported by any source. This is the fabrication problem that the module Evaluating Generative AI Applications measures.
Retrieval-augmented generation solves this by separating knowledge from reasoning. The organization's content is stored in a search index. At request time, the application searches the index for the passages most relevant to the question and places them in the prompt. The model is instructed to answer only from those passages and to cite them. The model contributes language understanding and synthesis; the index contributes the facts.
This separation has three practical consequences. First, updating knowledge means updating the index, which takes minutes, rather than retraining a model. Second, every answer can be traced to the passages it used, which lets users verify it and lets auditors review it. Third, access control can be applied at retrieval time, so a user only receives answers drawn from documents that the user is allowed to read.
RAG compared with fine-tuning and long prompts
Two alternatives are often proposed in exam scenarios. Fine-tuning trains a model on examples so that it adopts a style, format or behaviour. It is a poor way to add facts: the model cannot cite where a fact came from, the knowledge becomes outdated as soon as documents change, and retraining is slow and costly. Placing whole documents in the prompt works for a few short documents, but it does not scale to thousands of documents, it raises token cost on every request, and models attend less reliably to details buried in very long contexts. RAG sends only the few passages that matter.
The rule of thumb is therefore: use RAG to give a model knowledge, and use prompt engineering or fine-tuning to change how it behaves. The two can be combined, for example a fine-tuned model that answers in a regulated format from retrieved passages.
Where RAG is implemented
RAG can be implemented at three levels in Foundry, and the choice depends on how much control the application needs. The application can query Azure AI Search itself and call the model with the results, which this lesson shows and which gives full control over every step. An agent can be given a knowledge tool, such as the Azure AI Search tool or a Foundry IQ knowledge base, and decide for itself when to retrieve; the lesson Combining Retrieval, Function Calling and Memory in Agents covers this. A knowledge base with agentic retrieval can also plan several subqueries for a complex question, which the module Retrieval and Grounding Pipelines with Azure AI Search describes.
The request flow
A RAG request passes through five steps. Each step has its own failure modes, which is why RAG quality is evaluated step by step rather than only by looking at the final answer.
Query rewriting comes first because users ask follow-up questions that only make sense in context. "And for part-time staff?" retrieves nothing useful on its own. A small model call rewrites it, using the conversation history, into a standalone query such as "parental leave entitlement for part-time staff". Without this step, multi-turn conversations degrade after the first question.
Retrieval then runs the query against the index. The default pattern is a hybrid query, which combines keyword matching (good for names, codes and exact terms) with vector similarity (good for meaning and paraphrase), followed by the semantic ranker, which reorders the top results with a language-aware model. Filters restrict the results to documents the user may see and to relevant metadata, such as the current policy version. Only the top few chunks, typically three to ten, are kept.
Prompt construction places each chunk in the prompt with its source identifier, separated from the instructions by delimiters. The instructions tell the model to answer only from the sources, to cite the identifier of each source it uses, and to say so when the sources do not contain the answer. The delimiters also help the model treat retrieved text as data rather than as instructions, which reduces the risk of indirect prompt injection from documents.
Generation calls the model, usually at a low temperature, because a grounded answer should be faithful rather than creative. Returning the answer then maps the cited identifiers back to document titles and links, so that users can open the source. The following list summarizes the five steps.
-
Rewrite the query
Turn a follow-up such as "And for part-time staff?" into a standalone query using the conversation history.
-
Retrieve
Run a hybrid query (text plus vector) with semantic ranking and filters for permissions and metadata, and take the top chunks.
-
Build the prompt
Place each chunk with its source ID between delimiters, with instructions to answer only from the sources, cite them and say when the answer is not there.
-
Generate
Call the model, preferably at low temperature.
-
Return
Show the answer with citations linked to the source documents.
The following diagram places the steps alongside the services they use and the evaluators that measure them.

A RAG request
Retrieval code
With azure-search-documents, a hybrid query passes search_text and a VectorizableTextQuery, which uses the index's vectorizer to embed the query, and requests semantic ranking with a semantic configuration name. A filter restricts results to documents the user's groups may see.
In the following code, k_nearest_neighbors=50 asks the vector side of the query for 50 candidates, which are merged with the keyword results by Reciprocal Rank Fusion; the semantic ranker then reorders the merged list and top=5 keeps the best five chunks. The filter uses the search.in function on a collection field that stores the groups allowed to read each document, which is the usual way to implement security trimming. The retrieved chunks are joined with their IDs and passed to the Responses API inside <sources> tags, and the instructions require citations and an explicit statement when the answer is not in the sources.
from azure.search.documents import SearchClient
from azure.search.documents.models import VectorizableTextQuery
search = SearchClient(search_endpoint, "policies", credential)
results = search.search(
search_text=query,
vector_queries=[VectorizableTextQuery(text=query, k_nearest_neighbors=50, fields="content_vector")],
query_type="semantic", semantic_configuration_name="default",
filter=f"groups/any(g: search.in(g, '{','.join(user_groups)}'))",
select=["chunk_id", "title", "content"], top=5,
)
sources = "\n".join(f"[{r['chunk_id']}] {r['title']}: {r['content']}" for r in results)
answer = openai.responses.create(
model="chat-primary",
instructions=("Answer only from the sources. Cite source IDs in square brackets. "
"If the sources do not contain the answer, say that you don't know."),
input=f"<sources>\n{sources}\n</sources>\nQuestion: {query}",
)Tuning RAG
When a RAG application gives poor answers, the first question is whether the right content reached the model. If the relevant passage was not among the retrieved chunks, no prompt change can fix the answer, and the remedy lies in retrieval: hybrid search with the semantic ranker, more candidate chunks, better chunking or richer metadata. If the passage was retrieved but the answer still contains unsupported claims or ignores it, the problem lies in generation: the instructions allow the model to use its own knowledge, the temperature is too high, or too many irrelevant chunks dilute the relevant one.
Other symptoms point to missing design elements rather than poor tuning. Follow-up questions that fail indicate that query rewriting is missing. Answers that mix up product versions or superseded policies indicate that the index needs filterable metadata, such as a version or effective date, and that queries should filter on it. Users who see content from documents they may not read indicate that security trimming is missing, which is a security defect rather than a quality issue. High cost and latency usually come from sending too many or too long chunks, and are reduced by retrieving fewer, more relevant chunks or by using a smaller model.
The following table summarizes these symptoms, their likely causes and the adjustment for each.
| Symptom | Likely cause | Adjustment |
|---|---|---|
| Answer misses information that exists | Relevant chunk not retrieved | Hybrid plus semantic ranker, more chunks, better chunking |
| Answer includes unsupported claims | Prompt allows model knowledge | Stricter instructions, lower temperature, groundedness checks |
| Follow-up questions fail | Query lacks conversation context | Query rewriting with history |
| Answers mix up products or versions | No metadata filtering | Filterable metadata and filters |
| Users see documents they should not | No security trimming | Group filter at query time |
| Slow and expensive | Too many or too long chunks | Fewer, more relevant chunks; smaller model |
Tune the RAG solution
RAG that ignores new policies
An HR assistant answers "How many days of parental leave do I get?" with last year's figure, although the new policy is in the index. Both old and new policy documents are indexed.
Retrieval returns both versions and the model picks one. Add an effective-date or status field, filter to current documents (or remove superseded ones from the index), and instruct the model to prefer the most recent source when sources conflict. Fine-tuning on the new policy would not fix retrieval and would itself become outdated.
Why rewrite a follow-up question before retrieval?
Show answer
A follow-up such as "And for part-time staff?" means little on its own. Rewriting it into a standalone query with the conversation history lets retrieval find the right content.
Exam Tips
Remember for the exam
- Rewrite follow-up questions into standalone queries before retrieval.
- Hybrid query plus semantic ranking and permission filters is the default retrieval pattern.
- Instruct the model to answer only from sources, cite them and admit missing information.