CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 4 · Lesson 30/56

    Coding a simple RAG chain with LangChain and pyfunc

    Code a simple chain according to requirements

    16 min read
    1.47% of exam
    11 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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?

    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.

    Simple RAG chain steps in execution order
    StepWhat it doesRequirement 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 keywordsAmbiguous or misspelled queries, or filters hidden in the question
    2. RetrieveEmbeds the retrieval query, ranks chunks by similarity, and returns the top resultsHow many chunks to return; semantic vs keyword search
    3. Format context into a promptMerges the user query and retrieved chunks into a template with instructionsResponse format, such as citations or a fixed structure
    4. LLM generationGenerates an answer grounded on the augmented promptBalance of quality, latency and cost when picking the model
    5. Parse / post-process (optional)Applies business logic, adds citations, or refines the text by ruleDownstream 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. 1.Send the augmented prompt to the LLM to generate a grounded answer
    2. 2.Merge the user query and retrieved chunks into a prompt template with instructions
    3. 3.Rewrite the user query into a retrieval query (fix spelling, add synonyms)
    4. 4.Embed the retrieval query, rank chunks by similarity and return the top results
    5. 5.Post-process the LLM response to attach citations

    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?

    Sources23

    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.

    Retrieval step: a similarity search on a Delta Sync index with Databricks-computed embeddingspython
    # 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.

    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
        )

    Checkpoint 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?

    Sources415

    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.

    The LLM component: ChatDatabricks invoked on its ownpython
    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.

    A prompt, a model and an output parser piped into one runnablepython
    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()?

    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?

    Sources678

    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.

    Where each piece of a pyfunc-wrapped chain belongs
    CodeMethodReason
    Create the LLM client, load the prompt, build the chainload_contextNeeded once for the model to operate
    Strip and normalize the incoming querypredictRuns on every request, before the LLM call
    Retrieve, augment, generatepredictPer-request chain logic
    Reformat raw LLM output into a fixed schemapredictPost-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?

    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?

    Sources910

    Sources

    (11)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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
      “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. 2.
      “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. 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. 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. 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. 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. 9.
      “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
    8. 10.
      “For MLflow native flavor models, the necessary package dependencies are automatically captured.”
      ↩︎ Wrapping custom chain logic as a pyfunc

    Also cited

    Ready to test yourself?

    Practise the 6 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.