Hello! Welcome to your next lesson in the Retrieval-Augmented Generation (RAG) module.
Introduction
In our previous lesson, you successfully implemented the "Retrieval" component of a RAG system. You learned how to take a user's query, embed it, and use a Retriever to fetch the most relevant document chunks from a ChromaDB vector store. You now have the raw material—the context—needed to answer a user's question.
Today, we'll complete the core RAG pipeline by focusing on this lesson's learning outcome: to implement the generation component of a RAG system by combining retrieved context with a user query in a prompt.
We will tackle the "Augmentation" and "Generation" steps. This involves:
- Augmenting the user's query with the retrieved context by carefully constructing a prompt.
- Generating a final, context-aware answer by sending this augmented prompt to a Large Language Model (LLM).
As a backend engineer, you can think of this as building the final stage of a data processing pipeline: taking structured inputs (query and context) and transforming them into a final output (the answer).

The "Augmentation" and "Generation" Steps
At its core, the second half of the RAG process is straightforward:
- Augmentation: We create a prompt that includes instructions for the LLM, the context retrieved from our database, and the user's original question. This process "augments" the LLM's knowledge with specific, relevant information.
- Generation: We pass this augmented prompt to an LLM, which then generates a response that is grounded in the provided context, rather than relying solely on its internal training data.
We will use LangChain to orchestrate this process. LangChain's Expression Language (LCEL) allows us to define this flow declaratively, similar to how you might define a pipeline or a series of function compositions in backend development.
Building the RAG Chain with LCEL
The key to implementing this in code is to build a "chain" that connects our components: the retriever from the last lesson, a prompt template, and an LLM.
1. The Prompt Template
First, we need a template to structure our augmented prompt. This is a string with placeholders for the dynamic content—our context and the user's question.
The following video snippet gives a quick, clear demonstration of creating and using a prompt template for RAG.
RAG + Langchain Python Project: Easy AI/Chat For Your Docs
In this clip from the "RAG + Langchain Python Project" video by pixegami, you'll see a practical example of a prompt template designed for a RAG system. Notice how it explicitly tells the LLM to use the provided context to answer the question.
Watch from 12:47 to 13:42. Pay attention to the structure of the prompt_template and how the .format() method is used to insert the context and query.
A typical RAG prompt template in LangChain looks like this:
from langchain.prompts import ChatPromptTemplate
template = """
Answer the question based only on the following context:
{context}
Question: {input}
"""
prompt = ChatPromptTemplate.from_template(template)
This template has two input variables: context (for our retrieved documents) and input (for the user's query).
2. Composing the Chain
Now, let's assemble the full chain using LCEL's pipe (|) operator. The flow we want is:
- Take the user's query.
- Use the query to fetch context from the retriever.
- Simultaneously, pass the original query along.
- Feed both the context and the query into our prompt template.
- Pass the formatted prompt to the LLM.
- Get the final string output.
The following video provides an excellent, in-depth walkthrough of building exactly this chain. It's a bit longer, but it's invaluable for understanding how these components fit together in a real implementation.
Langchain RAG Course: From Basics to Production-Ready RAG Chatbot
The "Langchain RAG Course" by Pradip Nichite provides a fantastic, detailed walkthrough of building a RAG chain from scratch. This section shows how to connect the retriever, prompt, and LLM using LCEL, and even how to handle the formatting of retrieved documents.
Watch from 44:36 to 53:48. This is the most critical practical part of our lesson. Focus on how the rag_chain is constructed step-by-step: The creation of the prompt template with context and question placeholders. The use of a dictionary ({"context": ..., "question": ...}) to structure the input for the prompt. The use of RunnablePassthrough to forward the original query. The creation of a helper function to convert the list of retrieved Document objects into a single string. How all these components are piped together (|) to form the final chain.
3. Full Implementation
Let's combine what we've learned into a complete script. This script builds upon the retrieval component from the previous lesson.
import os
from dotenv import load_dotenv
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser
# 1. Load Environment Variables
load_dotenv()
# --- Re-use the retriever from the previous lesson ---
# Assuming you have the 'chroma_db' directory from the last lesson
vector_store = Chroma(
persist_directory="./chroma_db",
embedding_function=OpenAIEmbeddings()
)
retriever = vector_store.as_retriever(search_kwargs={'k': 3})
# --- Build the Generation Component ---
# 2. Define the Prompt Template
template = """
Answer the question based only on the following context:
{context}
Question: {input}
"""
prompt = ChatPromptTemplate.from_template(template)
# 3. Define the LLM
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
# 4. Helper function to format retrieved documents
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# 5. Construct the RAG Chain using LCEL
rag_chain = (
{
"context": retriever | format_docs, # Get context, then format it
"input": RunnablePassthrough() # Pass through the original input
}
| prompt
| llm
| StrOutputParser()
)
# --- Execute the Chain ---
# 6. Define a query and invoke the chain
query = "What did the president say about Putin?"
response = rag_chain.invoke(query)
print(f"Query: {query}\n")
print("RAG Response:")
print(response)
Code Breakdown:
format_docsfunction: Theretrieverreturns a list ofDocumentobjects. This simple function joins their content into a single string, which is what our prompt template expects for the{context}placeholder.- The
rag_chain: This is the core of our lesson.- The dictionary
{"context": ..., "input": ...}runs its components in parallel. "context": retriever | format_docs: The user's query goes to theretriever, its output (a list ofDocumentobjects) is piped toformat_docs, and the resulting string becomes the value forcontext."input": RunnablePassthrough():RunnablePassthroughis a utility that simply passes the input it receives (the original user query) along unchanged. This becomes the value forinput.- The resulting dictionary,
{'context': '...', 'input': '...'}is then piped to theprompt, then thellm, and finally theStrOutputParserwhich extracts the final string content from the LLM's response.
- The dictionary
Test your understanding!
In the rag_chain above, what would happen if you removed the | format_docs part from the context pipeline? Why would this cause an error?
Show answer
If you removed | format_docs, the retriever's output—a list of Document objects (e.g., [Document(...), Document(...)])—would be passed directly as the value for the context variable.
The prompt template expects a string for its {context} placeholder. When it tries to format itself with a list of objects instead of a string, it will likely raise a TypeError because it doesn't know how to render the list as text. The format_docs function is a crucial data transformation step that ensures the output of one component matches the expected input of the next.
Improving the Prompt: From Basic to Advanced
What we've built is functional, but a production-grade system requires more robust prompting. What if the context doesn't contain the answer? What if the user asks an irrelevant question?
This is where prompt engineering becomes critical. We can provide more detailed instructions to the LLM to handle these cases gracefully.
Improve RAG with Prompt Engineering - Ray Docs
Now that you have a working RAG chain, let's focus on making it more robust. The quality of your prompt is a critical factor. This article from the Ray documentation provides an excellent guide on improving RAG prompts by adding more sophisticated instructions.
First, read the section 'Basic RAG Prompt' and the three problems it identifies (Identity Exposure, Irrelevant User Request, Simple Answers). Then, carefully study the section 'Now let’s Upgrade to an Advanced Prompt'. Compare this advanced prompt with the basic one we used. Note the specific instructions given to the LLM to handle various scenarios, such as defining a persona, handling missing context, and refusing irrelevant requests. Finally, review 'Put the New Prompt in Action' to see how these changes solve the initial problems.
By adopting a more advanced prompt structure, you can significantly improve the reliability and quality of your RAG system's output. You would simply replace the basic template string in our code with this more detailed one.
Conclusion
Congratulations! You have now implemented a full, albeit simple, RAG pipeline. You can take a user's question, find relevant information in a private knowledge base, and generate a context-aware answer.
Key Takeaways:
- The generation component consists of Augmentation (creating a prompt with context and query) and Generation (calling the LLM).
- Prompt Templates are used to dynamically structure the input for the LLM.
- LangChain Expression Language (LCEL) provides a powerful, pipe-based syntax (
|) to chain components like retrievers, prompts, and LLMs. - The
{"context": retriever | format_docs, "input": RunnablePassthrough()}structure is a common and powerful pattern for building RAG chains in LCEL. - Prompt Engineering is crucial for building robust RAG systems. Adding explicit instructions for handling edge cases (like missing context or irrelevant questions) greatly improves performance.
Next Up:
Our current system is great for single question-and-answer interactions. However, it has no memory. If you ask a follow-up question, it treats it as a brand new query, completely unaware of the prior conversation.
In the next lesson, we will build an end-to-end RAG pipeline that can handle conversational context, allowing for more natural, multi-turn dialogues with your knowledge base.