pythonadvanced
LangChain RAG Retrieval Chain
Build a full RAG pipeline with source citations using LangChain's create_retrieval_chain.
pythonPress ⌘/Ctrl + Shift + C to copy
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.documents import Document
docs = [
Document(page_content='Python was created by Guido van Rossum.', metadata={'source': 'history.txt'}),
Document(page_content='FastAPI is a modern Python web framework.', metadata={'source': 'frameworks.txt'}),
Document(page_content='LangChain helps build LLM applications.', metadata={'source': 'tools.txt'}),
]
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
retriever = vectorstore.as_retriever()
prompt = ChatPromptTemplate.from_template('Answer based on context:\n{context}\n\nQuestion: {input}')
llm = ChatOpenAI(model='gpt-4o-mini')
doc_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, doc_chain)
result = rag_chain.invoke({'input': 'Who created Python?'})
print('Answer:', result['answer'])
print('Sources:', [d.metadata['source'] for d in result['context']])Use Cases
- RAG with citations
- document Q&A
- grounded answers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
LangChain RAG Chain Pipeline
Build a retrieval-augmented generation chain with LangChain using vector store retrieval and prompt templates.
Best for: Document Q&A
#langchain#rag
typescriptadvanced
RAG Pipeline Implementation
Build a retrieval-augmented generation pipeline that grounds LLM answers in your own documents.
Best for: Grounding LLM answers in private documents
#ai#rag
pythonadvanced
Build a RAG Pipeline with LangChain
Implement retrieval-augmented generation using LangChain, embeddings, and a vector store.
Best for: Knowledge base Q&A
#ai#langchain
pythonadvanced
RAG with FAISS and LangChain Python
Build a local RAG pipeline using FAISS vector store and LangChain for document Q&A.
Best for: document Q&A
#rag#faiss