AI / LangGraph LangChain Interview questions II
How do you build RAG pipelines with LangChain?
A RAG (Retrieval-Augmented Generation) pipeline enriches LLM responses with external knowledge by retrieving relevant documents at query time and injecting them into the prompt. A complete LangChain RAG pipeline has five stages:
- Load — ingest source documents with a DocumentLoader
- Split — chunk documents with a TextSplitter for efficient retrieval
- Embed & Store — embed chunks and store in a vector store
- Retrieve — at query time, fetch the most relevant chunks
- Generate — inject retrieved context into the prompt and generate an answer
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain import hub
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# 1. Load
loader = WebBaseLoader("https://python.langchain.com/docs/get_started/introduction")
docs = loader.load()
# 2. Split
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = splitter.split_documents(docs)
# 3. Embed & Store
vectorstore = Chroma.from_documents(chunks, OpenAIEmbeddings())
# 4 & 5. Retrieve + Generate
retriever = vectorstore.as_retriever()
rag_prompt = hub.pull("rlm/rag-prompt")
rag_chain = (
{"context": retriever | (lambda docs: "\n\n".join(d.page_content for d in docs)),
"question": RunnablePassthrough()}
| rag_prompt
| ChatOpenAI()
| StrOutputParser()
)
answer = rag_chain.invoke("What is LangChain?")
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
