pythonadvanced
RAG with FAISS and LangChain Python
Build a local RAG pipeline using FAISS vector store and LangChain for document Q&A.
pythonPress ⌘/Ctrl + Shift + C to copy
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
loader = TextLoader('document.txt')
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(chunks, embeddings)
vectorstore.save_local('faiss_index')
retriever = vectorstore.as_retriever(search_kwargs={'k': 4})
qa_chain = RetrievalQA.from_chain_type(llm=ChatOpenAI(model='gpt-4o-mini'), retriever=retriever)
result = qa_chain.invoke({'query': 'What is the main topic?'})
print(result['result'])Use Cases
- document Q&A
- local RAG
- knowledge base search
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
#rag#embeddings
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