Sub topic 8
Putting retrieval and generation together as RAG
This chapter assumes you can call a served chat model from Python and that you have a Vector Search index over a Delta table, as built in earlier chapters. You should also be comfortable with Python decorators.
What RAG does
Retrieval-augmented generation (RAG) is a pattern where the application fetches relevant text from your own data and passes it to the model along with the user's question. The model then answers from that text instead of relying only on what it learned in training.
RAG helps when answers depend on private or recent documents. It also gives you a way to check an answer, because you can see which chunks the model was given.
The request flow
Each request has two steps. The retrieval step runs a similarity search on the index and returns the top matching chunks. The generation step puts those chunks into the prompt and calls the chat model.
A minimal RAG function
The code below keeps retrieval and generation as two separate functions. The @mlflow.trace decorator records each call as a span, so one request produces one trace with the retrieval step and the generation step visible.
import mlflow
from databricks.sdk import WorkspaceClient
from databricks.vector_search.client import VectorSearchClient
ENDPOINT_NAME = "<your-chat-endpoint-name>"
client = WorkspaceClient().serving_endpoints.get_open_ai_client()
index = VectorSearchClient().get_index(
endpoint_name="<vector-search-endpoint>",
index_name="main.genai.docs_index",
)
@mlflow.trace(span_type="RETRIEVER")
def retrieve(question: str, k: int = 3) -> list[str]:
results = index.similarity_search(
query_text=question,
columns=["id", "text"],
num_results=k,
)
return [row[1] for row in results["result"]["data_array"]]
@mlflow.trace
def answer(question: str) -> str:
context = "\n\n".join(retrieve(question))
response = client.chat.completions.create(
model=ENDPOINT_NAME,
messages=[
{"role": "system", "content": "Answer using only the context below. If the answer is not there, say so.\n\n" + context},
{"role": "user", "content": question},
],
)
return response.choices[0].message.contentReplace the placeholder endpoint names with your own. Then call answer("How do I rotate an API key?") in a notebook. The trace appears under the cell output.
How the pieces work
- The
columnsargument selects which fields come back. Each row indata_arrayfollows that order, sorow[1]is thetextcolumn. - The
kvalue sets how many chunks you retrieve. Too few can miss the answer. Too many add noise and cost, and they fill the context window. - The system prompt tells the model to use only the context and to admit when the answer is missing. This instruction is the main guard against invented answers.
- The
RETRIEVERspan type labels the step so tools can treat it as a retrieval and show the returned documents.
Common errors
- Wrong column index. If you change
columns, update therow[1]lookup, or you will pass IDs to the model instead of text. - Empty context. If the index returns nothing, the model gets an empty context. The prompt should still tell it to say the answer is unavailable.
- Stale index. A Delta Sync index only reflects table changes after it syncs. With a
TRIGGEREDpipeline, you must start a sync to pick up new rows. - Poor chunks. If answers are weak, read the retrieved chunks in the trace before changing the prompt. Bad retrieval is the most common cause.
- Missing permissions. The identity running the code needs access to the index and the serving endpoint.
Exercise
Exercise
A RAG function returns confident but wrong answers. In the trace, the retrieval span shows chunks unrelated to the question. Which step do you fix first, and why?
Show answer
Fix retrieval first. The model can only ground its answer in the chunks it receives, so unrelated chunks lead to wrong answers regardless of the prompt. Check how the documents were chunked, whether the index has synced, and whether k is suitable. Adjust the prompt only after the right chunks are being returned.
Exercise
You change columns=["id", "text"] to columns=["text", "id"] and the model starts answering with strange identifiers. What went wrong, and how do you fix it?
Show answer
The code still reads row[1], which is now the id column. Change the lookup to row[0], or keep the original column order.