What you will be able to do
- Put the steps of a simple RAG chain in their fixed order and say which requirement shapes each one
- Compose a retriever, prompt template, ChatDatabricks model and output parser into one LangChain runnable with the pipe operator
- Expose a Unity Catalog function or a vector index to a LangChain chain as a tool
- Decide where pre-processing and post-processing code goes when a chain is wrapped as an MLflow pyfunc model
Key concept
Simple (deterministic) RAG chain — A RAG pipeline whose steps (take input, retrieve, format context into a prompt, call the LLM, parse the output) run in an order fixed in code. Every request follows that same path, and the LLM never chooses the next step.
1.A simple chain is fixed order written in code
A simple chain is a pipeline whose order you write yourself. You have already picked the components (see Chain components as an input-to-output pipeline). Coding the chain means wiring those components together in a fixed order so that every request takes the same route. In this design the developer decides which models and tools are called, in what order, and with which parameters. The model fills in text but never picks the next step.
That makes a basic RAG chain the deterministic case in the Deterministic chain vs single agent vs multi-agent supervisor spectrum. Databricks lists deterministic chains for well-defined tasks and static pipelines such as basic RAG, where nothing has to be decided on the fly. Because no LLM call is spent on routing, the chain usually has lower latency, is easy to audit and is easier to test. The cost is flexibility. A new capability means a code change, and the logic gets hard to maintain as branches pile up.
Checkpoint 1 of 9· Check yourself
A team is building an internal policy Q&A assistant on Databricks. The requirements: every request must follow the same auditable path, latency must be as low as possible, and every answer must be grounded in retrieved policy documents. Which design meets these requirements?
Basic RAG with a fixed path and low latency is the textbook deterministic chain. The developer fixes the order, so no LLM call is spent on routing, and the path is easy to audit. Agents, supervisors and LLM-driven branching all let the model choose the next step, which adds orchestration calls and makes the path less predictable.
“When you want to minimize latency by avoiding multiple LLM calls for orchestration decisions.”Source: docs.databricks.com
Sources1
2.The steps of a RAG chain and what shapes each one
A RAG chain at inference time follows one order: take the input, retrieve, format the context into a prompt, generate with the LLM, then parse or post-process. Two of these steps are optional. Query preprocessing at the start and post-processing at the end appear only when a requirement asks for them. Retrieval, prompt augmentation and generation are always there.
| Step | What it does | Requirement that shapes it |
|---|---|---|
| 1. Take input (optional preprocessing) | Turns the user query into a retrieval query by templating it, rewriting it with a model, or extracting keywords | Ambiguous or misspelled queries, or filters hidden in the question |
| 2. Retrieve | Embeds the retrieval query, ranks chunks by similarity, and returns the top results | How many chunks to return; semantic vs keyword search |
| 3. Format context into a prompt | Merges the user query and retrieved chunks into a template with instructions | Response format, such as citations or a fixed structure |
| 4. LLM generation | Generates an answer grounded on the augmented prompt | Balance of quality, latency and cost when picking the model |
| 5. Parse / post-process (optional) | Applies business logic, adds citations, or refines the text by rule | Downstream consumers that need a fixed shape |
Each step's output is the next step's input, so a change in one step reaches the others. Query rewriting changes what the retriever sees. Filter extraction also has to be done together with metadata extraction in the data pipeline, because the retriever can only filter on fields that exist on each chunk. The two numbers with the most effect on answer quality are both chain settings: how many chunks to retrieve in step 2 and how to combine them with the query in step 3.
Retrieval has one rule you cannot break. The query must be embedded with the same embedding model that embedded the document chunks during data preparation. A query vector from a different model is not comparable to the index, so similarity ranking returns noise even though nothing raises an error. Guardrails can be added at any point along the chain: request filtering before retrieval, permission checks before data sources are touched, and content moderation on the generated output.
Checkpoint 2 of 9· Put it in order
A support-docs RAG chain must fix misspelled questions and return answers with citations attached. Arrange its inference-time steps in execution order.
- 1.Send the augmented prompt to the LLM to generate a grounded answer
- 2.Merge the user query and retrieved chunks into a prompt template with instructions
- 3.Rewrite the user query into a retrieval query (fix spelling, add synonyms)
- 4.Embed the retrieval query, rank chunks by similarity and return the top results
- 5.Post-process the LLM response to attach citations
Query understanding runs first because retrieval needs its output. Retrieval comes before augmentation because the prompt is built from the retrieved chunks. Generation needs the augmented prompt, and post-processing works on the LLM's response, so it comes last.
“Understand the user's question. Retrieve supporting data. Augment the prompt with supporting data. Generate a response from an LLM using the augmented prompt.”Source: docs.databricks.com
Checkpoint 3 of 9· Check yourself
An engineer switches the query-side embedding endpoint of a working RAG chain to a newer model that outputs vectors of the same length. The index is not rebuilt. No errors appear, but answers now cite unrelated chunks. What is the cause?
The retrieval query must be embedded with the same model that embedded the chunks. Vectors from another model can have the same length and still not be comparable, so similarity ranking returns noise without raising an error.
“the retrieval query is translated into an embedding using the same embedding model that was used to embed the document chunks during data preparation”Source: docs.databricks.com
3.Coding the retriever and exposing tools
In code, the retrieval step is a query against an AI Search index (formerly Vector Search). An index gets its embeddings in one of two ways. A Delta Sync index with Databricks-computed embeddings embeds both the stored text and incoming queries for you. Direct-access indexes, and Delta Sync indexes with self-managed embeddings, leave that to you: you supply the vectors and the embedding model. For the first kind you pass the raw query text, the columns to return and num_results. Databricks embeds the text with the index's own model, which takes care of the same-model rule. num_results is where the requirement for how many chunks to retrieve goes.
# Delta Sync Index with embeddings computed by Databricks
results = index.similarity_search(
query_text="Greek myths",
columns=["id", "field2"],
num_results=2
)A tool is a function the model can request to have run, such as a search over an index or a lookup in a database. In a deterministic chain the developer still decides which tools or models are called, in what order and with which parameters, so a tool there is just another fixed step. The model only chooses which tools to call, and when, in an agent. The retrieval step above is exactly that: a fixed call that happens to be packaged as a tool.
Inside a LangChain application, the index can also be wrapped as a component. VectorSearchRetrieverTool from databricks-langchain (or databricks-openai) exposes an index as a tool. Its settings map straight onto the requirements: num_results, columns, filters, and query_type set to ANN or HYBRID. For direct-access indexes, or Delta Sync indexes with self-managed embeddings, you must also set text_column and embedding_model_name, and the embedding model has to be the one that created the index vectors. An index with Databricks-managed embeddings needs neither.
Business logic already registered in Unity Catalog, such as a Python function that looks up stock by SKU, enters a LangChain tool-calling chain through UCFunctionToolkit. The toolkit turns the registered Unity Catalog function into a tool the framework can call. Copying the function's source into the notebook breaks the link to the governed definition. Pre-querying a SQL view inside the prompt template, or packing outputs into an input example, does not give the model a tool to call at all.
Wrap the registered function with UCFunctionToolkit, which converts it into a LangChain-compatible tool that calls the Unity Catalog function directly.
Checkpoint 4 of 9· Fill the gap
This retrieval step queries a Delta Sync index where Databricks computes the embeddings. Which parameter should carry the user's question so the index embeds it with its own model?
# Delta Sync Index with embeddings computed by Databricks
results = index.similarity_search(
? ="Greek myths",
columns=["id", "field2"],
num_results=2
)When Databricks computes the embeddings, you pass the raw text as query_text. The index then embeds it with the same model that embedded the chunks, so the same-model rule is met. You would use query_vector only for an index with pre-calculated embeddings, where you embed the query yourself. query_type chooses between ANN and hybrid search, and filters limits which chunks can be returned.
Source: docs.databricks.comCheckpoint 5 of 9· Exam question
A team has written a Python function in Unity Catalog that looks up current inventory levels by SKU. They want a LangChain tool-calling agent chain to invoke this function as a tool during a conversation. Which approach correctly exposes the Unity Catalog function to the agent?
Correct answer: A — Load the function through UCFunctionToolkit using its catalog.schema.function name, then pass the resulting tools to the agent.
- A. Correct:
UCFunctionToolkittakes the registered function's three-level name and returns LangChain tools. When the tools are passed to the agent, the model can choose to call the inventory lookup during the conversation. - B. Incorrect: a helper that runs before the LLM call is ordinary application code, not a tool the agent can select. It also duplicates the governed Unity Catalog function in the notebook, and the model never decides when a SKU lookup is needed.
- C. Incorrect: a view is a different object from the registered function, and querying it inside the prompt template is a fixed step that runs before each model call. The agent cannot invoke the lookup on demand for a particular SKU, so it is not a tool.
- D. Incorrect: an
input_exampleonly records the expected input schema and a sample when the model is logged with MLflow. It gives the agent no callable function at inference time, so the SKU lookup cannot be invoked during a conversation.
4.Composing the chain with the LangChain pipe operator
The LLM step on Databricks is a ChatDatabricks chat model from databricks-langchain, pointed at a model service or serving endpoint. On its own it accepts messages and returns a chat message. It becomes a chain once a prompt template sits in front of it and an output parser sits behind it.
from langchain_core.messages import HumanMessage, SystemMessage
from databricks_langchain import ChatDatabricks
messages = [
SystemMessage(content="You're a helpful assistant"),
HumanMessage(content="What is a mixture of experts model?"),
]
llm = ChatDatabricks(model="system.ai.claude-sonnet-4-5")
llm.invoke(messages)LangChain Expression Language (LCEL) composes components with the pipe operator: prompt | llm | output_parser. The result is one runnable that you call with .invoke(). Data moves left to right. The ChatPromptTemplate fills its variables, ChatDatabricks generates, and StrOutputParser (from langchain_core.output_parsers) pulls out plain text. The order in the pipe is the order of execution, so the fixed order of the chain is literally the order of the expression.
prompt = PromptTemplate.from_template("Tell me a joke about {topic}.")
chain = prompt | llm | StrOutputParser()
chain.invoke({"topic": "artificial intelligence"})A RAG chain puts the retriever in front of the prompt. The first stage is a mapping, written as {"context": retriever | format_docs, "question": RunnablePassthrough()}. Its context entry sends the question through the retriever and then through format_docs, which turns the retrieved chunks into the text for the prompt's context variable. Its question entry uses RunnablePassthrough() to hand the raw question through unchanged to the question variable. Piping that mapping into prompt | llm | StrOutputParser() gives the full chain: retriever, prompt, model, parser. Older constructions such as LLMChain(...) or SequentialChain(chains=[...]) are not how LCEL composes runnables, and neither is building a RunnableSequence from a steps= list. The pipe is the idiom.
Checkpoint 6 of 9· Check yourself
Given the LCEL expression {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser(), what decides the order in which the steps run when you call .invoke()?
In LCEL, the order in the pipe is the order of execution, so the developer fixes the order of the chain in code and every request follows the same path. The model only generates text inside that path. It never picks the next step, so no LLM call is spent on orchestration.
“the developer defines which tools or models are called, in what order, and with which parameters”Source: docs.databricks.com
Checkpoint 7 of 9· Exam question
A generative AI engineer is assembling a simple chain in LangChain on Databricks that takes a user question, applies a ChatPromptTemplate, sends it to a ChatDatabricks LLM, and parses the output with a StrOutputParser. Which code correctly composes these three components into a single runnable chain using LangChain Expression Language?
Correct answer: A — Build the chain with prompt | llm | output_parser, which pipes each step's output into the next as one Runnable.
- A. Correct: the pipe operator is the standard LangChain Expression Language syntax. It builds a RunnableSequence in which the formatted prompt goes to the chat model and the model's message goes to the string parser.
- B. Incorrect:
LLMChainis a legacy Chain class, not an LCEL composition. It is deprecated in favour of piping Runnables, so it does not meet the requirement to compose the components with LangChain Expression Language. - C. Incorrect:
SequentialChainlinks legacy Chain objects through named input and output keys. A prompt template, a chat model and an output parser are Runnables, not Chains, so they cannot be listed in itschainsparameter. - D. Incorrect:
RunnableParallelis a real LCEL class, but it feeds the same input to every entry at once and returns a dict. The model would not receive the formatted prompt and the parser would not receive the model's output, so no sequential chain is built.
5.Wrapping custom chain logic as a pyfunc
MLflow packages a model through a flavor, which is a built-in way of logging models from one framework, such as mlflow.sklearn.log_model for scikit-learn. For models logged that way, the necessary package dependencies are captured automatically. Some requirements do not fit a built-in flavor: inputs that need cleaning before the model sees them, raw outputs that must be reshaped for a consumer, branching per request, or a framework MLflow doesn't support natively. In those cases you wrap the chain as an MLflow pyfunc, the generic option for arbitrary Python code. The two methods are covered in Pyfunc load_context and predict. What matters here is which code goes in which method.
The test is how often the code runs. Anything that should run once, such as loading artifacts, creating the client or building the chain object, goes in load_context, so that predict doesn't reload it on every call and inference stays fast. Anything that touches a specific request goes in predict, in chain order: normalize the query, run retrieval and the LLM, then reshape the raw output into the required schema before returning it. The model signature only describes input and output shapes and does no transforming. Model Serving has no separate post-scoring script either; post-processing is code inside predict.
| Code | Method | Reason |
|---|---|---|
| Create the LLM client, load the prompt, build the chain | load_context | Needed once for the model to operate |
| Strip and normalize the incoming query | predict | Runs on every request, before the LLM call |
| Retrieve, augment, generate | predict | Per-request chain logic |
| Reformat raw LLM output into a fixed schema | predict | Post-processing of each response |
Checkpoint 8 of 9· Check yourself
Inside a pyfunc-wrapped RAG chain, code strips whitespace from each incoming question and fixes its spelling. Where should that code run?
Normalization changes each request's query before retrieval, so it is per-request preprocessing and belongs at the start of predict. load_context runs once at load time, and the signature only describes input and output shapes; it doesn't transform anything.
“the user's query is preprocessed to make it more suitable for querying the vector database”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A generative AI engineer is coding a chain as an MLflow pyfunc model. The chain must strip and normalize incoming user queries before they reach the underlying LLM, and reformat the LLM's raw output into a fixed JSON schema before returning a response. Where should the engineer place this pre-processing and post-processing logic?
Correct answer: A — Implement the query cleanup and response shaping in predict, which is called for each scoring request.
- A. Correct:
predictis the method a pyfunc model calls for each scoring request, so it is where the LLM call can be wrapped with query normalization beforehand and JSON reformatting of the raw output afterward. - B. Incorrect:
load_contextruns a single time when the model is loaded, to set up artifacts such as the LLM client or prompt files. It never sees an individual incoming query or a specific LLM response, so it cannot transform them. - C. Incorrect: a model signature only declares the input and output column types and checks that requests match them. It cannot run code, so it cannot clean up the query text or restructure the LLM output.
- D. Incorrect:
code_pathsonly bundles extra files or modules with the logged model so they can be imported at serving time. It provides no hook that executes them on requests or responses, so the transformation still has to be called frompredict.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“The LLM does not make decisions about which tools to call or in what order.”
↩︎ A simple chain is fixed order written in code“Easier to test and validate.”
↩︎ A simple chain is fixed order written in code“the developer defines which tools or models are called, in what order, and with which parameters”
↩︎ Coding the retriever and exposing tools“The LLM does not make decisions about which tools to call or in what order.”
↩︎ Key concept“Static pipelines such as basic RAG No need for on-the-fly decisions”
↩︎ Exam trap 4“When you want to minimize latency by avoiding multiple LLM calls for orchestration decisions.”
↩︎ Checkpoint“the developer defines which tools or models are called, in what order, and with which parameters”
↩︎ Checkpoint - 2.https://docs.databricks.com/aws/en/agents/tutorials/ai-cookbook/fundamentals-inference-chain-ragOfficial docs
“The output of this step is a retrieval query which will be used in the subsequent retrieval step.”
↩︎ The steps of a RAG chain and what shapes each one“determining how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3”
↩︎ The steps of a RAG chain and what shapes each one“The LLM's response may be processed further to apply additional business logic, add citations, or otherwise refine the generated text”
↩︎ The steps of a RAG chain and what shapes each one“the retrieval query is translated into an embedding using the same embedding model that was used to embed the document chunks during data preparation”
↩︎ Exam trap 2“the retrieval query is translated into an embedding using the same embedding model that was used to embed the document chunks during data preparation”
↩︎ Checkpoint“the user's query is preprocessed to make it more suitable for querying the vector database”
↩︎ Checkpoint - 3.
“Query rewriting must be done in conjunction with changes to the retrieval component”
↩︎ The steps of a RAG chain and what shapes each one - 4.
“Use VectorSearchRetrieverTool from databricks-langchain or databricks-openai to expose an index as an agent tool.”
↩︎ Coding the retriever and exposing tools“Use the same embedding model that created the index vectors.”
↩︎ Coding the retriever and exposing tools“specify a custom embedding model and text column”
↩︎ Coding the retriever and exposing tools - 5.
“Each uses UCFunctionToolkit to call the function directly.”
↩︎ Coding the retriever and exposing tools“Each uses UCFunctionToolkit to call the function directly.”
↩︎ Exam trap 3 - 6.
“To query a model service using LangChain, you can use the ChatDatabricks ChatModel class and specify the model.”
↩︎ Composing the chain with the LangChain pipe operator - 7.
“from langchain_core.output_parsers import StrOutputParser”
↩︎ Composing the chain with the LangChain pipe operator - 8.
“chain = prompt | llm | StrOutputParser()”
↩︎ Composing the chain with the LangChain pipe operator - 9.https://docs.databricks.com/aws/en/machine-learning/model-serving/deploy-custom-python-codeOfficial docs
“Your model requires preprocessing before inputs can be passed to the model's predict function.”
↩︎ Wrapping custom chain logic as a pyfunc“Your application requires the model's raw outputs to be post-processed for consumption.”
↩︎ Wrapping custom chain logic as a pyfunc“predict - this function houses all the logic that is run every time an input request is made.”
↩︎ Wrapping custom chain logic as a pyfunc“load_context - anything that needs to be loaded just one time for the model to operate should be defined in this function.”
↩︎ Exam trap 1 - 10.
“For MLflow native flavor models, the necessary package dependencies are automatically captured.”
↩︎ Wrapping custom chain logic as a pyfunc
Also cited
“Understand the user's question. Retrieve supporting data. Augment the prompt with supporting data. Generate a response from an LLM using the augmented prompt.”
↩︎ Checkpoint